diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/flash/util/RectangleNode.as b/flash/util/RectangleNode.as new file mode 100644 index 0000000..6f31e44 --- /dev/null +++ b/flash/util/RectangleNode.as @@ -0,0 +1,178 @@ +package util { + import flash.geom.Rectangle; + + public class RectangleNode + { + public var Left:RectangleNode = null; + public var Right:RectangleNode = null; + public var Rect:Rectangle = null; + public var InUse:Boolean = false; + public var Removed:Boolean = false; + public var Parent:RectangleNode = null; + public var AllocationID = 0; + public var Host:RectanglePacker= null; + public var MinAllocationID = 0; + public var NodeID; + public static var NextNodeID = 0; + + public var DontRemove = false; + + public var LastAccessTime = 0; + + public var Flags = []; + + public var UpdateTo:RectangleNode = null; + + /* + public function get Removed() + { + return _Removed; + } + + public function set Removed(r) + { + this._Removed = r; + } + + public function get Host():RectanglePacker + { + return _Host; + } + public function set Host(p:RectanglePacker) + { + this._Host = p; + + if (_Left && _Left.Host != p) + { + throw new Error("bad left host"); + } + if (_Right && _Right.Host != p) + { + throw new Error("bad right host"); + } + if (_Parent && _Parent.Host != p) + { + throw new Error("bad parent host"); + } + + } + + public function get Left():RectangleNode + { + return _Left; + } + public function set Left(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad left host"); + } + _Left = n; + } + public function get Right():RectangleNode + { + return _Right; + } + public function set Right(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad right host"); + } + _Right = n; + } + + public function get Parent():RectangleNode + { + return _Parent; + } + public function set Parent(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad parent host"); + } + _Parent = n; + } + */ + public function get IsFreeSpace() + { + return Left == null && Right == null && !InUse; + } + public function UpdateLinksFromNode(node:RectangleNode) + { + if (node.Parent) + { + if (node.Parent.Left == node) + { + node.Parent.Left = this; + } + if (node.Parent.Right == node) + { + node.Parent.Right = this; + } + } + if (node.Left) + { + node.Left.Parent = this; + } + if (node.Right) + { + node.Right.Parent = this; + } + } + public function MakeFromNode(node:RectangleNode) + { + //_Host = node.Host; + Host = node.Host; + Left = node.Left; + Right = node.Right; + Parent = node.Parent; + AllocationID = node.AllocationID; + InUse = node.InUse; + MinAllocationID = node.MinAllocationID; + NodeID = node.NodeID; + Rect = node.Rect.clone(); + Removed = node.Removed; + DontRemove = node.DontRemove; + } + public function RectangleNode(x, y, w, h, host:RectanglePacker) + { + this.NodeID = NextNodeID++; + this.Host = host; + this.Rect = new Rectangle(x, y, w, h); + } + public function OutputJSON() + { + var node = {}; + node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; + node.in_use = InUse; + node.id = NodeID; + if (this.Left) node.left = this.Left.OutputJSON(); + if (this.Right) node.right = this.Right.OutputJSON(); + return node; + } + + public function ReadJSON(details) + { + details.new_node = this; + this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); + this.Removed = false; + + this.InUse = details.in_use; + + if (details.hasOwnProperty("right")) + { + this.Right = new RectangleNode(0, 0, 0, 0, this.Host); + Right.ReadJSON(details.right); + Right.Parent = this; + } + if (details.hasOwnProperty("left")) + { + this.Left = new RectangleNode(0, 0, 0, 0, this.Host); + Left.ReadJSON(details.left); + Left.Parent = this; + } + } + } +} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/flash/util/RectangleNode.as b/flash/util/RectangleNode.as new file mode 100644 index 0000000..6f31e44 --- /dev/null +++ b/flash/util/RectangleNode.as @@ -0,0 +1,178 @@ +package util { + import flash.geom.Rectangle; + + public class RectangleNode + { + public var Left:RectangleNode = null; + public var Right:RectangleNode = null; + public var Rect:Rectangle = null; + public var InUse:Boolean = false; + public var Removed:Boolean = false; + public var Parent:RectangleNode = null; + public var AllocationID = 0; + public var Host:RectanglePacker= null; + public var MinAllocationID = 0; + public var NodeID; + public static var NextNodeID = 0; + + public var DontRemove = false; + + public var LastAccessTime = 0; + + public var Flags = []; + + public var UpdateTo:RectangleNode = null; + + /* + public function get Removed() + { + return _Removed; + } + + public function set Removed(r) + { + this._Removed = r; + } + + public function get Host():RectanglePacker + { + return _Host; + } + public function set Host(p:RectanglePacker) + { + this._Host = p; + + if (_Left && _Left.Host != p) + { + throw new Error("bad left host"); + } + if (_Right && _Right.Host != p) + { + throw new Error("bad right host"); + } + if (_Parent && _Parent.Host != p) + { + throw new Error("bad parent host"); + } + + } + + public function get Left():RectangleNode + { + return _Left; + } + public function set Left(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad left host"); + } + _Left = n; + } + public function get Right():RectangleNode + { + return _Right; + } + public function set Right(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad right host"); + } + _Right = n; + } + + public function get Parent():RectangleNode + { + return _Parent; + } + public function set Parent(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad parent host"); + } + _Parent = n; + } + */ + public function get IsFreeSpace() + { + return Left == null && Right == null && !InUse; + } + public function UpdateLinksFromNode(node:RectangleNode) + { + if (node.Parent) + { + if (node.Parent.Left == node) + { + node.Parent.Left = this; + } + if (node.Parent.Right == node) + { + node.Parent.Right = this; + } + } + if (node.Left) + { + node.Left.Parent = this; + } + if (node.Right) + { + node.Right.Parent = this; + } + } + public function MakeFromNode(node:RectangleNode) + { + //_Host = node.Host; + Host = node.Host; + Left = node.Left; + Right = node.Right; + Parent = node.Parent; + AllocationID = node.AllocationID; + InUse = node.InUse; + MinAllocationID = node.MinAllocationID; + NodeID = node.NodeID; + Rect = node.Rect.clone(); + Removed = node.Removed; + DontRemove = node.DontRemove; + } + public function RectangleNode(x, y, w, h, host:RectanglePacker) + { + this.NodeID = NextNodeID++; + this.Host = host; + this.Rect = new Rectangle(x, y, w, h); + } + public function OutputJSON() + { + var node = {}; + node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; + node.in_use = InUse; + node.id = NodeID; + if (this.Left) node.left = this.Left.OutputJSON(); + if (this.Right) node.right = this.Right.OutputJSON(); + return node; + } + + public function ReadJSON(details) + { + details.new_node = this; + this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); + this.Removed = false; + + this.InUse = details.in_use; + + if (details.hasOwnProperty("right")) + { + this.Right = new RectangleNode(0, 0, 0, 0, this.Host); + Right.ReadJSON(details.right); + Right.Parent = this; + } + if (details.hasOwnProperty("left")) + { + this.Left = new RectangleNode(0, 0, 0, 0, this.Host); + Left.ReadJSON(details.left); + Left.Parent = this; + } + } + } +} diff --git a/flash/util/RectanglePacker.as b/flash/util/RectanglePacker.as new file mode 100644 index 0000000..597d7fd --- /dev/null +++ b/flash/util/RectanglePacker.as @@ -0,0 +1,562 @@ +package util { + import flash.geom.*; + import flash.display.BitmapData; + import flash.display.MovieClip; + import flash.text.TextField; + import flash.events.*; + import flash.sampler.StackFrame; + + public class RectanglePacker + { + protected var w:int; + protected var h:int; + protected var root:RectangleNode; + public var NextAllocationID = 0; + + public function get width():int { return w; } + public function get height():int { return h; } + + public function RectanglePacker(w, h) + { + this.w = w; + this.h = h; + root = new RectangleNode(0, 0, w, h, this); + root.AllocationID = -1; + } + protected var area = 0; + + protected var testRender:MovieClip = new MovieClip(); + + public function GetRoot():RectangleNode + { + return root; + } + + public function GetLeafNodes():Array + { + return GetLeafNodesInternal(root); + } + + protected function GetLeafNodesInternal(n:RectangleNode):Array + { + if (n.InUse) return [n]; + var ret:Array = new Array(); + if (n.Left) ret = GetLeafNodesInternal(n.Left); + if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); + return ret; + } + + public function GetUsedArea() + { + return area; + } + + public function get efficiency() + { + return area / (w * h); + } + + protected function RectCost(w, h) + { + if (w == 0 || h == 0) return 99999999; + return (Math.max(w, h) / Math.min(w, h)) * w * h; + } + + protected function EnumerateTree(r:RectangleNode = null, indent = "") + { + if (r == null) r = this.root; + var str = ""; + str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; + if (r.Left) str += EnumerateTree(r.Left, indent + " "); + if (r.Right) str += EnumerateTree(r.Left, indent + " "); + return str; + } + + /* + * Remove a list of nodes from the tree. + * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree + * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, + leaving the original objects intact (in case something still references them) + */ + public function RemoveNodes(nodes:Array, fullyDestroy = true) + { + + /* DEBUG CHECKS */ + /* + this.PerformDebugCheck(); + + var str = ""; + for (var i = 0; i < nodes.length; i++) + { + str += nodes[i].NodeID + "\n"; + } + + var orig = nodes.concat(); + + var strs = [str, EnumerateTree()]; + + RenderDetailsBox.StartTrack("PackRemoveTime"); + + for (var i = 0; i < nodes.length; i++) + { + var n:RectangleNode = nodes[i]; + if (n.Host != this) + { + throw new Error("bad host!"); + } + } + */ + /* END DEBUG CHECKS */ + + var i, n:RectangleNode, p:RectangleNode; + + // setup the Removed flag on every node that should be removed + // we also check at this time to see if any more nodes need to be removed, such as a parent of + // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + if (n.Host == this) + { + n.Removed = true; + + if (n.InUse) + { + // sum up the total removed area + area -= n.Rect.width * n.Rect.height; + } + + if (n.Parent != null) + { + p = n.Parent; + // check and see if the current node's parent still has any valid children + if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) + { + // all of the current nodes siblings are either being removed or are blank, so + // we can remove the parent too + if (p.Left.IsFreeSpace) + { + // the left child was empty space before, so we can remove it (if it wasn't + // empty space it is already being removed so it doesn't need to be added + // to the list) + if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); + } + if (p.Right.IsFreeSpace) + { + // the right child was empty space before, so we can remove it + if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); + } + if (p != root && nodes.indexOf(p) == -1) + { + // remove the parent node too (provided it isn't the root!) + nodes.push(p); + } + } + } + } + } + + // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, + // so go ahead and remove them + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + + if (n.Parent != null) + { + // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not + // also getting removed!) + p = n.Parent; + + if (!p.Removed) + { + if (p.Left && p.Right) + { + var newNode:RectangleNode; + if (p.Left.Removed && p.Right.Removed) + { + // both children were removed, but the parent wasn't, so the parent must be root + // (since we never remove the root) + if (p != root) + { + throw new Error("should be root"); + } + p.Left.Parent = null; + p.Right.Parent = null; + p.Left = null; + p.Right = null; + p.InUse = false; + } else if (!p.Left.Removed) { + // Right node removed, Left node not removed + if (!p.Left.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Right); + newNode.UpdateLinksFromNode(p.Right); + } + // Left node is used + p.Right.InUse = false; + p.Right.Left = null; + p.Right.Right = null; + p.Right.Removed = false; + } else { + throw new Error("should have been caught above!"); + } + } else { + // Left node removed, Right node not removed + if (!p.Right.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Left); + newNode.UpdateLinksFromNode(p.Left); + } + // Left node is used + //p.Left.Removed = true; + p.Left.InUse = false; + p.Left.Left = null; + p.Left.Right = null; + p.Left.Removed = false; + //p.Left.Parent = null; + } else { + throw new Error("should have been caught above!"); + } + } + } else { + // huh? how does n.Parent == p but p has no children? something went wrong + throw new Error("shouldn't have gotten here"); + } + } + } + //strs.push(EnumerateTree()); + } + } + + public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode + { + + var node:RectangleNode = FindSizedNode(w, h, root); + + if (node == null) + { + //UHOH, texture full + return null; + } + area += w * h; + node.InUse = true; + + var splitVertFirstCost = 0; + if (w < node.Rect.width) + { + splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); + } + + var splitHorizFirstCost = 0; + if (h < node.Rect.height) + { + splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); + } + + + + if (splitVertFirstCost <= splitHorizFirstCost) + { + node.Flags.push("SplitVertFirst"); + if (w < node.Rect.width) + { + node.Flags.push("SplitVert"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + if (h < node.Rect.height) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + } else { + node.Flags.push("SplitHorzFirst"); + if (h < node.Rect.height) + { + node.Flags.push("SplitVert"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + if (w < node.Rect.width) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + } + NextAllocationID++; + if (useInstead) + { + useInstead.MakeFromNode(node); + useInstead.UpdateLinksFromNode(node); + useInstead.Flags = node.Flags; + node = useInstead; + node.Flags.push("UseInstead"); + } + + //if (!CheckOKNode(node)) node.Flags.push("BadNode"); + + return node; + } + public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) + { + if (r == null) r = this.root; + if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) + { + var ancestor:RectangleNode = FindCommonNode(n, r); + throw new Error("bad node allocated!"); + return false; + } + var ok = true; + if (r.Left) ok = ok && CheckOKNode(n, r.Left); + if (r.Right) ok = ok && CheckOKNode(n, r.Right); + return ok; + } + + public function PerformDebugCheck() + { + DebugInternal(this.root); + } + + protected function DebugInternal(n:RectangleNode) + { + if (n.Host != this) + { + throw new Error("problem with host!"); + } + if (n.IsFreeSpace) + { + if (n.Left || n.Right) + { + throw new Error("shouldn't have children"); + } + } + if ((n.Left && !n.Right) || (n.Right && !n.Left)) + { + throw new Error("mismatched children"); + } + if (n.Left && n.Left.Parent != n) + { + throw new Error("left child has bad parent"); + } + if (n.Right && n.Right.Parent != n) + { + throw new Error("right child has bad parent"); + } + if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) + { + throw new Error("problem with parent"); + } + if (n.Left) DebugInternal(n.Left); + if (n.Right) DebugInternal(n.Right); + } + + public function FindCommonNode(a:RectangleNode, b:RectangleNode) + { + var aHistory = []; + var bHistory = []; + while (a != null) + { + aHistory.push(a); + a = a.Parent; + } + while (b != null) + { + bHistory.push(b); + b = b.Parent; + } + var i = aHistory.length - 1; + var j = bHistory.length - 1; + var same = null; + while (i >= 0 && j >= 0) + { + if (aHistory[i] == bHistory[j]) + { + same = aHistory[i]; + } else { + break; + } + i--; + j--; + } + return same; + } + + public function TestRender() + { + while (testRender.numChildren > 0) + { + testRender.removeChildAt(0); + } + testRender.graphics.clear(); + TestRenderNode(root, testRender); + return testRender; + } + protected function TestRenderNode(n:RectangleNode, m:MovieClip) + { + var g:MovieClip = new MovieClip(); + m.addChild(g); + g.graphics.lineStyle(1, 0, 1); + if (n.Left != null) TestRenderNode(n.Left, m); + if (n.Left != null) TestRenderNode(n.Right, m); + if (n.InUse) + { + g.graphics.beginFill(0xFFFF00, 0.2); + } + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + if (n.InUse) + { + g.graphics.endFill(); + var t:TextField = new TextField(); + t.text = n.NodeID; + t.x = n.Rect.x + n.Rect.width / 2.0; + t.y = n.Rect.y + n.Rect.height / 2.0; + g.addChild(t); + g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); + g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); + } + + } + public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) + { + if (n.InUse) + { + //_trace(Math.round(n.LastAccessTime / 1000)); + } + var p:RectangleNode = n.Parent; + if (p) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); + g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); + g.graphics.endFill(); + t.text = p.NodeID; + if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); + g.oldListener = function(e){MouseOver(p, g, t);}; + g.addEventListener(MouseEvent.CLICK, g.oldListener); + } + } + public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(0xFFFF00, 0.2); + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + g.graphics.endFill(); + t.text = n.NodeID; + } + protected function SplitVert(node:RectangleNode, leftWidth) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function SplitHoriz(node:RectangleNode, topHeight) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode + { + if (node.InUse) return null; + if (node.Rect.width >= w && node.Rect.height >= h) + { + if (node.Left != null && node.Right != null) + { + var t:RectangleNode = FindSizedNode(w, h, node.Left); + if (t != null) return t; + t = FindSizedNode(w, h, node.Right); + return t; + } else { + return node; + } + } + return null; + } + + public function LoadTree(details) + { + this.root = new RectangleNode(0, 0, 0, 0, this); + root.ReadJSON(details); + + this.NextAllocationID = 0; + this.area = 0; + + var queue:Array = new Array(); + queue.push(root); + while (queue.length > 0) + { + var node:RectangleNode = queue.shift(); + node.AllocationID = NextAllocationID; + node.MinAllocationID = NextAllocationID; + if (node.Left) queue.push(node.Left); + if (node.Right) queue.push(node.Right); + if (node.InUse) this.area += node.Rect.width * node.Rect.height; + } + NextAllocationID++; + } + + public function GetNodePath(node:RectangleNode) + { + var output:String = ""; + while (node != this.root) + { + output = (node == node.Parent.Left ? "l" : "r") + output; + node = node.Parent; + } + return output; + } + + public function GetNodeFromPath(path:String):RectangleNode + { + var node:RectangleNode = this.root; + for (var i = 0; i < path.length; i++) + { + if (!node) return null; + if (path.charAt(i) == "r") + { + node = node.Right; + } else { + node = node.Left; + } + } + return node; + } + } +} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/flash/util/RectangleNode.as b/flash/util/RectangleNode.as new file mode 100644 index 0000000..6f31e44 --- /dev/null +++ b/flash/util/RectangleNode.as @@ -0,0 +1,178 @@ +package util { + import flash.geom.Rectangle; + + public class RectangleNode + { + public var Left:RectangleNode = null; + public var Right:RectangleNode = null; + public var Rect:Rectangle = null; + public var InUse:Boolean = false; + public var Removed:Boolean = false; + public var Parent:RectangleNode = null; + public var AllocationID = 0; + public var Host:RectanglePacker= null; + public var MinAllocationID = 0; + public var NodeID; + public static var NextNodeID = 0; + + public var DontRemove = false; + + public var LastAccessTime = 0; + + public var Flags = []; + + public var UpdateTo:RectangleNode = null; + + /* + public function get Removed() + { + return _Removed; + } + + public function set Removed(r) + { + this._Removed = r; + } + + public function get Host():RectanglePacker + { + return _Host; + } + public function set Host(p:RectanglePacker) + { + this._Host = p; + + if (_Left && _Left.Host != p) + { + throw new Error("bad left host"); + } + if (_Right && _Right.Host != p) + { + throw new Error("bad right host"); + } + if (_Parent && _Parent.Host != p) + { + throw new Error("bad parent host"); + } + + } + + public function get Left():RectangleNode + { + return _Left; + } + public function set Left(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad left host"); + } + _Left = n; + } + public function get Right():RectangleNode + { + return _Right; + } + public function set Right(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad right host"); + } + _Right = n; + } + + public function get Parent():RectangleNode + { + return _Parent; + } + public function set Parent(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad parent host"); + } + _Parent = n; + } + */ + public function get IsFreeSpace() + { + return Left == null && Right == null && !InUse; + } + public function UpdateLinksFromNode(node:RectangleNode) + { + if (node.Parent) + { + if (node.Parent.Left == node) + { + node.Parent.Left = this; + } + if (node.Parent.Right == node) + { + node.Parent.Right = this; + } + } + if (node.Left) + { + node.Left.Parent = this; + } + if (node.Right) + { + node.Right.Parent = this; + } + } + public function MakeFromNode(node:RectangleNode) + { + //_Host = node.Host; + Host = node.Host; + Left = node.Left; + Right = node.Right; + Parent = node.Parent; + AllocationID = node.AllocationID; + InUse = node.InUse; + MinAllocationID = node.MinAllocationID; + NodeID = node.NodeID; + Rect = node.Rect.clone(); + Removed = node.Removed; + DontRemove = node.DontRemove; + } + public function RectangleNode(x, y, w, h, host:RectanglePacker) + { + this.NodeID = NextNodeID++; + this.Host = host; + this.Rect = new Rectangle(x, y, w, h); + } + public function OutputJSON() + { + var node = {}; + node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; + node.in_use = InUse; + node.id = NodeID; + if (this.Left) node.left = this.Left.OutputJSON(); + if (this.Right) node.right = this.Right.OutputJSON(); + return node; + } + + public function ReadJSON(details) + { + details.new_node = this; + this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); + this.Removed = false; + + this.InUse = details.in_use; + + if (details.hasOwnProperty("right")) + { + this.Right = new RectangleNode(0, 0, 0, 0, this.Host); + Right.ReadJSON(details.right); + Right.Parent = this; + } + if (details.hasOwnProperty("left")) + { + this.Left = new RectangleNode(0, 0, 0, 0, this.Host); + Left.ReadJSON(details.left); + Left.Parent = this; + } + } + } +} diff --git a/flash/util/RectanglePacker.as b/flash/util/RectanglePacker.as new file mode 100644 index 0000000..597d7fd --- /dev/null +++ b/flash/util/RectanglePacker.as @@ -0,0 +1,562 @@ +package util { + import flash.geom.*; + import flash.display.BitmapData; + import flash.display.MovieClip; + import flash.text.TextField; + import flash.events.*; + import flash.sampler.StackFrame; + + public class RectanglePacker + { + protected var w:int; + protected var h:int; + protected var root:RectangleNode; + public var NextAllocationID = 0; + + public function get width():int { return w; } + public function get height():int { return h; } + + public function RectanglePacker(w, h) + { + this.w = w; + this.h = h; + root = new RectangleNode(0, 0, w, h, this); + root.AllocationID = -1; + } + protected var area = 0; + + protected var testRender:MovieClip = new MovieClip(); + + public function GetRoot():RectangleNode + { + return root; + } + + public function GetLeafNodes():Array + { + return GetLeafNodesInternal(root); + } + + protected function GetLeafNodesInternal(n:RectangleNode):Array + { + if (n.InUse) return [n]; + var ret:Array = new Array(); + if (n.Left) ret = GetLeafNodesInternal(n.Left); + if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); + return ret; + } + + public function GetUsedArea() + { + return area; + } + + public function get efficiency() + { + return area / (w * h); + } + + protected function RectCost(w, h) + { + if (w == 0 || h == 0) return 99999999; + return (Math.max(w, h) / Math.min(w, h)) * w * h; + } + + protected function EnumerateTree(r:RectangleNode = null, indent = "") + { + if (r == null) r = this.root; + var str = ""; + str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; + if (r.Left) str += EnumerateTree(r.Left, indent + " "); + if (r.Right) str += EnumerateTree(r.Left, indent + " "); + return str; + } + + /* + * Remove a list of nodes from the tree. + * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree + * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, + leaving the original objects intact (in case something still references them) + */ + public function RemoveNodes(nodes:Array, fullyDestroy = true) + { + + /* DEBUG CHECKS */ + /* + this.PerformDebugCheck(); + + var str = ""; + for (var i = 0; i < nodes.length; i++) + { + str += nodes[i].NodeID + "\n"; + } + + var orig = nodes.concat(); + + var strs = [str, EnumerateTree()]; + + RenderDetailsBox.StartTrack("PackRemoveTime"); + + for (var i = 0; i < nodes.length; i++) + { + var n:RectangleNode = nodes[i]; + if (n.Host != this) + { + throw new Error("bad host!"); + } + } + */ + /* END DEBUG CHECKS */ + + var i, n:RectangleNode, p:RectangleNode; + + // setup the Removed flag on every node that should be removed + // we also check at this time to see if any more nodes need to be removed, such as a parent of + // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + if (n.Host == this) + { + n.Removed = true; + + if (n.InUse) + { + // sum up the total removed area + area -= n.Rect.width * n.Rect.height; + } + + if (n.Parent != null) + { + p = n.Parent; + // check and see if the current node's parent still has any valid children + if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) + { + // all of the current nodes siblings are either being removed or are blank, so + // we can remove the parent too + if (p.Left.IsFreeSpace) + { + // the left child was empty space before, so we can remove it (if it wasn't + // empty space it is already being removed so it doesn't need to be added + // to the list) + if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); + } + if (p.Right.IsFreeSpace) + { + // the right child was empty space before, so we can remove it + if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); + } + if (p != root && nodes.indexOf(p) == -1) + { + // remove the parent node too (provided it isn't the root!) + nodes.push(p); + } + } + } + } + } + + // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, + // so go ahead and remove them + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + + if (n.Parent != null) + { + // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not + // also getting removed!) + p = n.Parent; + + if (!p.Removed) + { + if (p.Left && p.Right) + { + var newNode:RectangleNode; + if (p.Left.Removed && p.Right.Removed) + { + // both children were removed, but the parent wasn't, so the parent must be root + // (since we never remove the root) + if (p != root) + { + throw new Error("should be root"); + } + p.Left.Parent = null; + p.Right.Parent = null; + p.Left = null; + p.Right = null; + p.InUse = false; + } else if (!p.Left.Removed) { + // Right node removed, Left node not removed + if (!p.Left.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Right); + newNode.UpdateLinksFromNode(p.Right); + } + // Left node is used + p.Right.InUse = false; + p.Right.Left = null; + p.Right.Right = null; + p.Right.Removed = false; + } else { + throw new Error("should have been caught above!"); + } + } else { + // Left node removed, Right node not removed + if (!p.Right.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Left); + newNode.UpdateLinksFromNode(p.Left); + } + // Left node is used + //p.Left.Removed = true; + p.Left.InUse = false; + p.Left.Left = null; + p.Left.Right = null; + p.Left.Removed = false; + //p.Left.Parent = null; + } else { + throw new Error("should have been caught above!"); + } + } + } else { + // huh? how does n.Parent == p but p has no children? something went wrong + throw new Error("shouldn't have gotten here"); + } + } + } + //strs.push(EnumerateTree()); + } + } + + public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode + { + + var node:RectangleNode = FindSizedNode(w, h, root); + + if (node == null) + { + //UHOH, texture full + return null; + } + area += w * h; + node.InUse = true; + + var splitVertFirstCost = 0; + if (w < node.Rect.width) + { + splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); + } + + var splitHorizFirstCost = 0; + if (h < node.Rect.height) + { + splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); + } + + + + if (splitVertFirstCost <= splitHorizFirstCost) + { + node.Flags.push("SplitVertFirst"); + if (w < node.Rect.width) + { + node.Flags.push("SplitVert"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + if (h < node.Rect.height) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + } else { + node.Flags.push("SplitHorzFirst"); + if (h < node.Rect.height) + { + node.Flags.push("SplitVert"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + if (w < node.Rect.width) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + } + NextAllocationID++; + if (useInstead) + { + useInstead.MakeFromNode(node); + useInstead.UpdateLinksFromNode(node); + useInstead.Flags = node.Flags; + node = useInstead; + node.Flags.push("UseInstead"); + } + + //if (!CheckOKNode(node)) node.Flags.push("BadNode"); + + return node; + } + public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) + { + if (r == null) r = this.root; + if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) + { + var ancestor:RectangleNode = FindCommonNode(n, r); + throw new Error("bad node allocated!"); + return false; + } + var ok = true; + if (r.Left) ok = ok && CheckOKNode(n, r.Left); + if (r.Right) ok = ok && CheckOKNode(n, r.Right); + return ok; + } + + public function PerformDebugCheck() + { + DebugInternal(this.root); + } + + protected function DebugInternal(n:RectangleNode) + { + if (n.Host != this) + { + throw new Error("problem with host!"); + } + if (n.IsFreeSpace) + { + if (n.Left || n.Right) + { + throw new Error("shouldn't have children"); + } + } + if ((n.Left && !n.Right) || (n.Right && !n.Left)) + { + throw new Error("mismatched children"); + } + if (n.Left && n.Left.Parent != n) + { + throw new Error("left child has bad parent"); + } + if (n.Right && n.Right.Parent != n) + { + throw new Error("right child has bad parent"); + } + if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) + { + throw new Error("problem with parent"); + } + if (n.Left) DebugInternal(n.Left); + if (n.Right) DebugInternal(n.Right); + } + + public function FindCommonNode(a:RectangleNode, b:RectangleNode) + { + var aHistory = []; + var bHistory = []; + while (a != null) + { + aHistory.push(a); + a = a.Parent; + } + while (b != null) + { + bHistory.push(b); + b = b.Parent; + } + var i = aHistory.length - 1; + var j = bHistory.length - 1; + var same = null; + while (i >= 0 && j >= 0) + { + if (aHistory[i] == bHistory[j]) + { + same = aHistory[i]; + } else { + break; + } + i--; + j--; + } + return same; + } + + public function TestRender() + { + while (testRender.numChildren > 0) + { + testRender.removeChildAt(0); + } + testRender.graphics.clear(); + TestRenderNode(root, testRender); + return testRender; + } + protected function TestRenderNode(n:RectangleNode, m:MovieClip) + { + var g:MovieClip = new MovieClip(); + m.addChild(g); + g.graphics.lineStyle(1, 0, 1); + if (n.Left != null) TestRenderNode(n.Left, m); + if (n.Left != null) TestRenderNode(n.Right, m); + if (n.InUse) + { + g.graphics.beginFill(0xFFFF00, 0.2); + } + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + if (n.InUse) + { + g.graphics.endFill(); + var t:TextField = new TextField(); + t.text = n.NodeID; + t.x = n.Rect.x + n.Rect.width / 2.0; + t.y = n.Rect.y + n.Rect.height / 2.0; + g.addChild(t); + g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); + g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); + } + + } + public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) + { + if (n.InUse) + { + //_trace(Math.round(n.LastAccessTime / 1000)); + } + var p:RectangleNode = n.Parent; + if (p) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); + g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); + g.graphics.endFill(); + t.text = p.NodeID; + if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); + g.oldListener = function(e){MouseOver(p, g, t);}; + g.addEventListener(MouseEvent.CLICK, g.oldListener); + } + } + public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(0xFFFF00, 0.2); + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + g.graphics.endFill(); + t.text = n.NodeID; + } + protected function SplitVert(node:RectangleNode, leftWidth) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function SplitHoriz(node:RectangleNode, topHeight) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode + { + if (node.InUse) return null; + if (node.Rect.width >= w && node.Rect.height >= h) + { + if (node.Left != null && node.Right != null) + { + var t:RectangleNode = FindSizedNode(w, h, node.Left); + if (t != null) return t; + t = FindSizedNode(w, h, node.Right); + return t; + } else { + return node; + } + } + return null; + } + + public function LoadTree(details) + { + this.root = new RectangleNode(0, 0, 0, 0, this); + root.ReadJSON(details); + + this.NextAllocationID = 0; + this.area = 0; + + var queue:Array = new Array(); + queue.push(root); + while (queue.length > 0) + { + var node:RectangleNode = queue.shift(); + node.AllocationID = NextAllocationID; + node.MinAllocationID = NextAllocationID; + if (node.Left) queue.push(node.Left); + if (node.Right) queue.push(node.Right); + if (node.InUse) this.area += node.Rect.width * node.Rect.height; + } + NextAllocationID++; + } + + public function GetNodePath(node:RectangleNode) + { + var output:String = ""; + while (node != this.root) + { + output = (node == node.Parent.Left ? "l" : "r") + output; + node = node.Parent; + } + return output; + } + + public function GetNodeFromPath(path:String):RectangleNode + { + var node:RectangleNode = this.root; + for (var i = 0; i < path.length; i++) + { + if (!node) return null; + if (path.charAt(i) == "r") + { + node = node.Right; + } else { + node = node.Left; + } + } + return node; + } + } +} diff --git a/flash/util/Utils.as b/flash/util/Utils.as new file mode 100644 index 0000000..f792003 --- /dev/null +++ b/flash/util/Utils.as @@ -0,0 +1,389 @@ +package util +{ + import flash.display.*; + import flash.geom.*; + public class Utils + { + public static function GetChildren(clip:MovieClip):Array + { + var ret:Array = []; + for (var i = 0; i < clip.numChildren; i++) + { + ret.push(clip.getChildAt(i)); + } + return ret; + } + + /* + * angle difference + * (range -Math.PI to Math.PI) + */ + public static function GetAngleDiff(a, b) + { + var angleDiff = b - a; + + while (angleDiff > Math.PI) + { + angleDiff -= Math.PI * 2; + } + while (angleDiff < -Math.PI) + { + angleDiff += Math.PI * 2; + } + return angleDiff; + } + + /* + * angle difference + * (range 0 to Math.PI) + */ + public static function GetAngleDiffAbs(a, b) + { + var angleDiff = GetAngleDiff(a, b); + while (angleDiff < 0) + { + angleDiff += Math.PI * 2; + } + + if (angleDiff > Math.PI) + { + angleDiff = Math.PI * 2 - angleDiff; + } + + return angleDiff; + } + + public static function GetTransform(from:Matrix, to:Matrix) + { + var i:Matrix = from.clone(); + i.invert(); + var m:Matrix = to.clone(); + m.concat(i); + return m; + } + + public static function Decompose(m:Matrix) + { + var s:Point = ScaleFromMat(m); + m = m.clone(); + + var sxUnit = s.x >= 0 ? 1 : -1; + var syUnit = s.y >= 0 ? 1 : -1; + + m.scale(sxUnit, syUnit); + + //m.a /= sxUnit; + //m.d /= syUnit; + var rot = RotFromMat(m); + return {sx:s.x, sy:s.y, rot:rot}; + } + + public static function RotFromMat(m:Matrix) + { + return Math.atan2(-m.c, m.a); + } + + public static function ScaleFromMat(m:Matrix):Point + { + var xAxisX = m.a; + var xAxisY = m.c; + + var yAxisX = m.b; + var yAxisY = m.d; + + var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); + if (m.a < 0) sx *= -1; + + var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); + if (m.d < 0) sy *= -1; + + return new Point(sx, sy); + } + + public static function TransformRect(r:Rectangle, m:Matrix) + { + var p1:Point = new Point(r.left, r.top); + var p2:Point = new Point(r.right, r.top); + var p3:Point = new Point(r.left, r.bottom); + var p4:Point = new Point(r.right, r.bottom); + + p1 = m.transformPoint(p1); + p2 = m.transformPoint(p2); + p3 = m.transformPoint(p3); + p4 = m.transformPoint(p4); + + r.left = Math.min(p1.x, p2.x, p3.x, p4.x); + r.top = Math.min(p1.y, p2.y, p3.y, p4.y); + r.right = Math.max(p1.x, p2.x, p3.x, p4.x); + r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); + } + + public static function RoundRect(r:Rectangle) + { + r.left = Math.floor(r.left); + r.top = Math.floor(r.top); + r.right = Math.ceil(r.right); + r.bottom = Math.ceil(r.bottom); + } + + public static function ScaleRect(r:Rectangle, s) + { + r.left *= s; + r.top *= s; + r.right *= s; + r.bottom *= s; + } + + public static function RecursivelyStop(clip) + { + if (clip is MovieClip) + { + clip.stop(); + } + if (clip is DisplayObjectContainer) + { + for (var i = 0; i < clip.numChildren; i++) + { + RecursivelyStop(clip.getChildAt(i)); + } + } + } + + public static function WeirdGotoFrame(clip:MovieClip, frame) + { + var dir = clip.currentFrame > frame ? -1 : 1; + while (clip.currentFrame != frame) + { + RecurseDir(clip, dir); + } + } + + protected static function RecurseDir(clip:MovieClip, dir) + { + for (var i = 0; i < clip.numChildren; i++) + { + var child = clip.getChildAt(i); + if (child is MovieClip) + { + RecurseDir(child, dir); + } + } + if (dir == 1) + { + clip.nextFrame(); + } else { + clip.prevFrame(); + } + } + + protected static var tempSpace:BitmapData = null; + protected static var tempSpaceRect:Rectangle = new Rectangle(); + protected static var tempSpaceMatrix:Matrix = new Matrix(); + protected static var tempSpaceZero:Point = new Point(); + protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); + protected static var lastDrawOffset:Point = new Point(); + public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle + { + if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); + + var oldPad = 0; + var padAmount = 5; + + var ret:Rectangle = new Rectangle(); + + var baseBounds:Rectangle = clip.getBounds(clip); + + var boundsClip:DisplayObject = null; + if (clip is DisplayObjectContainer) + { + boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); + } + + if (boundsClip != null) + { + baseBounds = boundsClip.getBounds(clip); + } + + if (useMatrix) + { + TransformAABBRect(baseBounds, useMatrix); + } + + if (boundsClip != null) + { + return baseBounds; + } + + var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); + var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); + if (tempSpace == null) + { + tempSpace = new BitmapData(minW, minH, true, 0x0); + } + if (tempSpace.width < minW || tempSpace.height < minH) + { + tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); + } + + var r:Rectangle = new Rectangle(); + + baseBounds.left = Math.floor(baseBounds.left); + baseBounds.right = Math.ceil(baseBounds.right); + + baseBounds.top = Math.floor(baseBounds.top); + baseBounds.bottom = Math.ceil(baseBounds.bottom); + + var i; + + var needsChecking = true; + while (needsChecking) + { + needsChecking = false; + r.left = baseBounds.left - padAmount; + r.right = baseBounds.right + padAmount; + + r.top = baseBounds.top - padAmount; + r.bottom = baseBounds.bottom + padAmount; + + ret = r.clone(); + + tempSpaceRect.x = tempSpaceRect.y = 0; + tempSpaceRect.width = tempSpace.width; + tempSpaceRect.height = tempSpace.height; + tempSpace.fillRect(tempSpaceRect, 0x0); + + tempSpaceMatrix.identity(); + if (useMatrix) + { + tempSpaceMatrix.a = useMatrix.a; + tempSpaceMatrix.b = useMatrix.b; + tempSpaceMatrix.c = useMatrix.c; + tempSpaceMatrix.d = useMatrix.d; + tempSpaceMatrix.tx = useMatrix.tx; + tempSpaceMatrix.ty = useMatrix.ty; + } + tempSpaceMatrix.translate(-r.left, -r.top); + + lastDrawOffset.x = -r.left; + lastDrawOffset.y = -r.top; + tempSpace.draw(clip, tempSpaceMatrix); + + tempSpaceRect.width = 1; + tempSpaceRect.height = r.height; + + var sideMovedIn = 0; + for (i = 0; i < r.width; i++) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.left++; + sideMovedIn++; + } + } + if (ret.left < baseBounds.left - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.width - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.right--; + } + } + if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + sideMovedIn = 0; + tempSpaceRect.width = r.width; + tempSpaceRect.height = 1; + tempSpaceRect.x = 0; + for (i = 0; i < r.height; i++) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.top++; + sideMovedIn++; + } + } + if (ret.top < baseBounds.top - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.height - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.bottom--; + } + } + if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + } + return ret; + } + + public static function TransformAABBRect(r:Rectangle, m:Matrix) + { + var o1X = r.left; + var o1Y = r.top; + + var o2X = r.right; + var o2Y = r.top; + + var o3X = r.left; + var o3Y = r.bottom; + + var o4X = r.right; + var o4Y = r.bottom; + + var n1X = o1X * m.a + o1Y * m.c + m.tx; + var n1Y = o1X * m.b + o1Y * m.d + m.ty; + + var n2X = o2X * m.a + o2Y * m.c + m.tx; + var n2Y = o2X * m.b + o2Y * m.d + m.ty; + + var n3X = o3X * m.a + o3Y * m.c + m.tx; + var n3Y = o3X * m.b + o3Y * m.d + m.ty; + + var n4X = o4X * m.a + o4Y * m.c + m.tx; + var n4Y = o4X * m.b + o4Y * m.d + m.ty; + + r.left = Math.min(n1X, n2X, n3X, n4X); + r.right = Math.max(n1X, n2X, n3X, n4X); + + r.top = Math.min(n1Y, n2Y, n3Y, n4Y); + r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); + } + } +} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/flash/util/RectangleNode.as b/flash/util/RectangleNode.as new file mode 100644 index 0000000..6f31e44 --- /dev/null +++ b/flash/util/RectangleNode.as @@ -0,0 +1,178 @@ +package util { + import flash.geom.Rectangle; + + public class RectangleNode + { + public var Left:RectangleNode = null; + public var Right:RectangleNode = null; + public var Rect:Rectangle = null; + public var InUse:Boolean = false; + public var Removed:Boolean = false; + public var Parent:RectangleNode = null; + public var AllocationID = 0; + public var Host:RectanglePacker= null; + public var MinAllocationID = 0; + public var NodeID; + public static var NextNodeID = 0; + + public var DontRemove = false; + + public var LastAccessTime = 0; + + public var Flags = []; + + public var UpdateTo:RectangleNode = null; + + /* + public function get Removed() + { + return _Removed; + } + + public function set Removed(r) + { + this._Removed = r; + } + + public function get Host():RectanglePacker + { + return _Host; + } + public function set Host(p:RectanglePacker) + { + this._Host = p; + + if (_Left && _Left.Host != p) + { + throw new Error("bad left host"); + } + if (_Right && _Right.Host != p) + { + throw new Error("bad right host"); + } + if (_Parent && _Parent.Host != p) + { + throw new Error("bad parent host"); + } + + } + + public function get Left():RectangleNode + { + return _Left; + } + public function set Left(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad left host"); + } + _Left = n; + } + public function get Right():RectangleNode + { + return _Right; + } + public function set Right(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad right host"); + } + _Right = n; + } + + public function get Parent():RectangleNode + { + return _Parent; + } + public function set Parent(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad parent host"); + } + _Parent = n; + } + */ + public function get IsFreeSpace() + { + return Left == null && Right == null && !InUse; + } + public function UpdateLinksFromNode(node:RectangleNode) + { + if (node.Parent) + { + if (node.Parent.Left == node) + { + node.Parent.Left = this; + } + if (node.Parent.Right == node) + { + node.Parent.Right = this; + } + } + if (node.Left) + { + node.Left.Parent = this; + } + if (node.Right) + { + node.Right.Parent = this; + } + } + public function MakeFromNode(node:RectangleNode) + { + //_Host = node.Host; + Host = node.Host; + Left = node.Left; + Right = node.Right; + Parent = node.Parent; + AllocationID = node.AllocationID; + InUse = node.InUse; + MinAllocationID = node.MinAllocationID; + NodeID = node.NodeID; + Rect = node.Rect.clone(); + Removed = node.Removed; + DontRemove = node.DontRemove; + } + public function RectangleNode(x, y, w, h, host:RectanglePacker) + { + this.NodeID = NextNodeID++; + this.Host = host; + this.Rect = new Rectangle(x, y, w, h); + } + public function OutputJSON() + { + var node = {}; + node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; + node.in_use = InUse; + node.id = NodeID; + if (this.Left) node.left = this.Left.OutputJSON(); + if (this.Right) node.right = this.Right.OutputJSON(); + return node; + } + + public function ReadJSON(details) + { + details.new_node = this; + this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); + this.Removed = false; + + this.InUse = details.in_use; + + if (details.hasOwnProperty("right")) + { + this.Right = new RectangleNode(0, 0, 0, 0, this.Host); + Right.ReadJSON(details.right); + Right.Parent = this; + } + if (details.hasOwnProperty("left")) + { + this.Left = new RectangleNode(0, 0, 0, 0, this.Host); + Left.ReadJSON(details.left); + Left.Parent = this; + } + } + } +} diff --git a/flash/util/RectanglePacker.as b/flash/util/RectanglePacker.as new file mode 100644 index 0000000..597d7fd --- /dev/null +++ b/flash/util/RectanglePacker.as @@ -0,0 +1,562 @@ +package util { + import flash.geom.*; + import flash.display.BitmapData; + import flash.display.MovieClip; + import flash.text.TextField; + import flash.events.*; + import flash.sampler.StackFrame; + + public class RectanglePacker + { + protected var w:int; + protected var h:int; + protected var root:RectangleNode; + public var NextAllocationID = 0; + + public function get width():int { return w; } + public function get height():int { return h; } + + public function RectanglePacker(w, h) + { + this.w = w; + this.h = h; + root = new RectangleNode(0, 0, w, h, this); + root.AllocationID = -1; + } + protected var area = 0; + + protected var testRender:MovieClip = new MovieClip(); + + public function GetRoot():RectangleNode + { + return root; + } + + public function GetLeafNodes():Array + { + return GetLeafNodesInternal(root); + } + + protected function GetLeafNodesInternal(n:RectangleNode):Array + { + if (n.InUse) return [n]; + var ret:Array = new Array(); + if (n.Left) ret = GetLeafNodesInternal(n.Left); + if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); + return ret; + } + + public function GetUsedArea() + { + return area; + } + + public function get efficiency() + { + return area / (w * h); + } + + protected function RectCost(w, h) + { + if (w == 0 || h == 0) return 99999999; + return (Math.max(w, h) / Math.min(w, h)) * w * h; + } + + protected function EnumerateTree(r:RectangleNode = null, indent = "") + { + if (r == null) r = this.root; + var str = ""; + str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; + if (r.Left) str += EnumerateTree(r.Left, indent + " "); + if (r.Right) str += EnumerateTree(r.Left, indent + " "); + return str; + } + + /* + * Remove a list of nodes from the tree. + * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree + * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, + leaving the original objects intact (in case something still references them) + */ + public function RemoveNodes(nodes:Array, fullyDestroy = true) + { + + /* DEBUG CHECKS */ + /* + this.PerformDebugCheck(); + + var str = ""; + for (var i = 0; i < nodes.length; i++) + { + str += nodes[i].NodeID + "\n"; + } + + var orig = nodes.concat(); + + var strs = [str, EnumerateTree()]; + + RenderDetailsBox.StartTrack("PackRemoveTime"); + + for (var i = 0; i < nodes.length; i++) + { + var n:RectangleNode = nodes[i]; + if (n.Host != this) + { + throw new Error("bad host!"); + } + } + */ + /* END DEBUG CHECKS */ + + var i, n:RectangleNode, p:RectangleNode; + + // setup the Removed flag on every node that should be removed + // we also check at this time to see if any more nodes need to be removed, such as a parent of + // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + if (n.Host == this) + { + n.Removed = true; + + if (n.InUse) + { + // sum up the total removed area + area -= n.Rect.width * n.Rect.height; + } + + if (n.Parent != null) + { + p = n.Parent; + // check and see if the current node's parent still has any valid children + if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) + { + // all of the current nodes siblings are either being removed or are blank, so + // we can remove the parent too + if (p.Left.IsFreeSpace) + { + // the left child was empty space before, so we can remove it (if it wasn't + // empty space it is already being removed so it doesn't need to be added + // to the list) + if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); + } + if (p.Right.IsFreeSpace) + { + // the right child was empty space before, so we can remove it + if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); + } + if (p != root && nodes.indexOf(p) == -1) + { + // remove the parent node too (provided it isn't the root!) + nodes.push(p); + } + } + } + } + } + + // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, + // so go ahead and remove them + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + + if (n.Parent != null) + { + // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not + // also getting removed!) + p = n.Parent; + + if (!p.Removed) + { + if (p.Left && p.Right) + { + var newNode:RectangleNode; + if (p.Left.Removed && p.Right.Removed) + { + // both children were removed, but the parent wasn't, so the parent must be root + // (since we never remove the root) + if (p != root) + { + throw new Error("should be root"); + } + p.Left.Parent = null; + p.Right.Parent = null; + p.Left = null; + p.Right = null; + p.InUse = false; + } else if (!p.Left.Removed) { + // Right node removed, Left node not removed + if (!p.Left.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Right); + newNode.UpdateLinksFromNode(p.Right); + } + // Left node is used + p.Right.InUse = false; + p.Right.Left = null; + p.Right.Right = null; + p.Right.Removed = false; + } else { + throw new Error("should have been caught above!"); + } + } else { + // Left node removed, Right node not removed + if (!p.Right.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Left); + newNode.UpdateLinksFromNode(p.Left); + } + // Left node is used + //p.Left.Removed = true; + p.Left.InUse = false; + p.Left.Left = null; + p.Left.Right = null; + p.Left.Removed = false; + //p.Left.Parent = null; + } else { + throw new Error("should have been caught above!"); + } + } + } else { + // huh? how does n.Parent == p but p has no children? something went wrong + throw new Error("shouldn't have gotten here"); + } + } + } + //strs.push(EnumerateTree()); + } + } + + public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode + { + + var node:RectangleNode = FindSizedNode(w, h, root); + + if (node == null) + { + //UHOH, texture full + return null; + } + area += w * h; + node.InUse = true; + + var splitVertFirstCost = 0; + if (w < node.Rect.width) + { + splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); + } + + var splitHorizFirstCost = 0; + if (h < node.Rect.height) + { + splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); + } + + + + if (splitVertFirstCost <= splitHorizFirstCost) + { + node.Flags.push("SplitVertFirst"); + if (w < node.Rect.width) + { + node.Flags.push("SplitVert"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + if (h < node.Rect.height) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + } else { + node.Flags.push("SplitHorzFirst"); + if (h < node.Rect.height) + { + node.Flags.push("SplitVert"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + if (w < node.Rect.width) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + } + NextAllocationID++; + if (useInstead) + { + useInstead.MakeFromNode(node); + useInstead.UpdateLinksFromNode(node); + useInstead.Flags = node.Flags; + node = useInstead; + node.Flags.push("UseInstead"); + } + + //if (!CheckOKNode(node)) node.Flags.push("BadNode"); + + return node; + } + public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) + { + if (r == null) r = this.root; + if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) + { + var ancestor:RectangleNode = FindCommonNode(n, r); + throw new Error("bad node allocated!"); + return false; + } + var ok = true; + if (r.Left) ok = ok && CheckOKNode(n, r.Left); + if (r.Right) ok = ok && CheckOKNode(n, r.Right); + return ok; + } + + public function PerformDebugCheck() + { + DebugInternal(this.root); + } + + protected function DebugInternal(n:RectangleNode) + { + if (n.Host != this) + { + throw new Error("problem with host!"); + } + if (n.IsFreeSpace) + { + if (n.Left || n.Right) + { + throw new Error("shouldn't have children"); + } + } + if ((n.Left && !n.Right) || (n.Right && !n.Left)) + { + throw new Error("mismatched children"); + } + if (n.Left && n.Left.Parent != n) + { + throw new Error("left child has bad parent"); + } + if (n.Right && n.Right.Parent != n) + { + throw new Error("right child has bad parent"); + } + if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) + { + throw new Error("problem with parent"); + } + if (n.Left) DebugInternal(n.Left); + if (n.Right) DebugInternal(n.Right); + } + + public function FindCommonNode(a:RectangleNode, b:RectangleNode) + { + var aHistory = []; + var bHistory = []; + while (a != null) + { + aHistory.push(a); + a = a.Parent; + } + while (b != null) + { + bHistory.push(b); + b = b.Parent; + } + var i = aHistory.length - 1; + var j = bHistory.length - 1; + var same = null; + while (i >= 0 && j >= 0) + { + if (aHistory[i] == bHistory[j]) + { + same = aHistory[i]; + } else { + break; + } + i--; + j--; + } + return same; + } + + public function TestRender() + { + while (testRender.numChildren > 0) + { + testRender.removeChildAt(0); + } + testRender.graphics.clear(); + TestRenderNode(root, testRender); + return testRender; + } + protected function TestRenderNode(n:RectangleNode, m:MovieClip) + { + var g:MovieClip = new MovieClip(); + m.addChild(g); + g.graphics.lineStyle(1, 0, 1); + if (n.Left != null) TestRenderNode(n.Left, m); + if (n.Left != null) TestRenderNode(n.Right, m); + if (n.InUse) + { + g.graphics.beginFill(0xFFFF00, 0.2); + } + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + if (n.InUse) + { + g.graphics.endFill(); + var t:TextField = new TextField(); + t.text = n.NodeID; + t.x = n.Rect.x + n.Rect.width / 2.0; + t.y = n.Rect.y + n.Rect.height / 2.0; + g.addChild(t); + g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); + g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); + } + + } + public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) + { + if (n.InUse) + { + //_trace(Math.round(n.LastAccessTime / 1000)); + } + var p:RectangleNode = n.Parent; + if (p) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); + g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); + g.graphics.endFill(); + t.text = p.NodeID; + if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); + g.oldListener = function(e){MouseOver(p, g, t);}; + g.addEventListener(MouseEvent.CLICK, g.oldListener); + } + } + public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(0xFFFF00, 0.2); + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + g.graphics.endFill(); + t.text = n.NodeID; + } + protected function SplitVert(node:RectangleNode, leftWidth) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function SplitHoriz(node:RectangleNode, topHeight) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode + { + if (node.InUse) return null; + if (node.Rect.width >= w && node.Rect.height >= h) + { + if (node.Left != null && node.Right != null) + { + var t:RectangleNode = FindSizedNode(w, h, node.Left); + if (t != null) return t; + t = FindSizedNode(w, h, node.Right); + return t; + } else { + return node; + } + } + return null; + } + + public function LoadTree(details) + { + this.root = new RectangleNode(0, 0, 0, 0, this); + root.ReadJSON(details); + + this.NextAllocationID = 0; + this.area = 0; + + var queue:Array = new Array(); + queue.push(root); + while (queue.length > 0) + { + var node:RectangleNode = queue.shift(); + node.AllocationID = NextAllocationID; + node.MinAllocationID = NextAllocationID; + if (node.Left) queue.push(node.Left); + if (node.Right) queue.push(node.Right); + if (node.InUse) this.area += node.Rect.width * node.Rect.height; + } + NextAllocationID++; + } + + public function GetNodePath(node:RectangleNode) + { + var output:String = ""; + while (node != this.root) + { + output = (node == node.Parent.Left ? "l" : "r") + output; + node = node.Parent; + } + return output; + } + + public function GetNodeFromPath(path:String):RectangleNode + { + var node:RectangleNode = this.root; + for (var i = 0; i < path.length; i++) + { + if (!node) return null; + if (path.charAt(i) == "r") + { + node = node.Right; + } else { + node = node.Left; + } + } + return node; + } + } +} diff --git a/flash/util/Utils.as b/flash/util/Utils.as new file mode 100644 index 0000000..f792003 --- /dev/null +++ b/flash/util/Utils.as @@ -0,0 +1,389 @@ +package util +{ + import flash.display.*; + import flash.geom.*; + public class Utils + { + public static function GetChildren(clip:MovieClip):Array + { + var ret:Array = []; + for (var i = 0; i < clip.numChildren; i++) + { + ret.push(clip.getChildAt(i)); + } + return ret; + } + + /* + * angle difference + * (range -Math.PI to Math.PI) + */ + public static function GetAngleDiff(a, b) + { + var angleDiff = b - a; + + while (angleDiff > Math.PI) + { + angleDiff -= Math.PI * 2; + } + while (angleDiff < -Math.PI) + { + angleDiff += Math.PI * 2; + } + return angleDiff; + } + + /* + * angle difference + * (range 0 to Math.PI) + */ + public static function GetAngleDiffAbs(a, b) + { + var angleDiff = GetAngleDiff(a, b); + while (angleDiff < 0) + { + angleDiff += Math.PI * 2; + } + + if (angleDiff > Math.PI) + { + angleDiff = Math.PI * 2 - angleDiff; + } + + return angleDiff; + } + + public static function GetTransform(from:Matrix, to:Matrix) + { + var i:Matrix = from.clone(); + i.invert(); + var m:Matrix = to.clone(); + m.concat(i); + return m; + } + + public static function Decompose(m:Matrix) + { + var s:Point = ScaleFromMat(m); + m = m.clone(); + + var sxUnit = s.x >= 0 ? 1 : -1; + var syUnit = s.y >= 0 ? 1 : -1; + + m.scale(sxUnit, syUnit); + + //m.a /= sxUnit; + //m.d /= syUnit; + var rot = RotFromMat(m); + return {sx:s.x, sy:s.y, rot:rot}; + } + + public static function RotFromMat(m:Matrix) + { + return Math.atan2(-m.c, m.a); + } + + public static function ScaleFromMat(m:Matrix):Point + { + var xAxisX = m.a; + var xAxisY = m.c; + + var yAxisX = m.b; + var yAxisY = m.d; + + var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); + if (m.a < 0) sx *= -1; + + var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); + if (m.d < 0) sy *= -1; + + return new Point(sx, sy); + } + + public static function TransformRect(r:Rectangle, m:Matrix) + { + var p1:Point = new Point(r.left, r.top); + var p2:Point = new Point(r.right, r.top); + var p3:Point = new Point(r.left, r.bottom); + var p4:Point = new Point(r.right, r.bottom); + + p1 = m.transformPoint(p1); + p2 = m.transformPoint(p2); + p3 = m.transformPoint(p3); + p4 = m.transformPoint(p4); + + r.left = Math.min(p1.x, p2.x, p3.x, p4.x); + r.top = Math.min(p1.y, p2.y, p3.y, p4.y); + r.right = Math.max(p1.x, p2.x, p3.x, p4.x); + r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); + } + + public static function RoundRect(r:Rectangle) + { + r.left = Math.floor(r.left); + r.top = Math.floor(r.top); + r.right = Math.ceil(r.right); + r.bottom = Math.ceil(r.bottom); + } + + public static function ScaleRect(r:Rectangle, s) + { + r.left *= s; + r.top *= s; + r.right *= s; + r.bottom *= s; + } + + public static function RecursivelyStop(clip) + { + if (clip is MovieClip) + { + clip.stop(); + } + if (clip is DisplayObjectContainer) + { + for (var i = 0; i < clip.numChildren; i++) + { + RecursivelyStop(clip.getChildAt(i)); + } + } + } + + public static function WeirdGotoFrame(clip:MovieClip, frame) + { + var dir = clip.currentFrame > frame ? -1 : 1; + while (clip.currentFrame != frame) + { + RecurseDir(clip, dir); + } + } + + protected static function RecurseDir(clip:MovieClip, dir) + { + for (var i = 0; i < clip.numChildren; i++) + { + var child = clip.getChildAt(i); + if (child is MovieClip) + { + RecurseDir(child, dir); + } + } + if (dir == 1) + { + clip.nextFrame(); + } else { + clip.prevFrame(); + } + } + + protected static var tempSpace:BitmapData = null; + protected static var tempSpaceRect:Rectangle = new Rectangle(); + protected static var tempSpaceMatrix:Matrix = new Matrix(); + protected static var tempSpaceZero:Point = new Point(); + protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); + protected static var lastDrawOffset:Point = new Point(); + public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle + { + if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); + + var oldPad = 0; + var padAmount = 5; + + var ret:Rectangle = new Rectangle(); + + var baseBounds:Rectangle = clip.getBounds(clip); + + var boundsClip:DisplayObject = null; + if (clip is DisplayObjectContainer) + { + boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); + } + + if (boundsClip != null) + { + baseBounds = boundsClip.getBounds(clip); + } + + if (useMatrix) + { + TransformAABBRect(baseBounds, useMatrix); + } + + if (boundsClip != null) + { + return baseBounds; + } + + var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); + var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); + if (tempSpace == null) + { + tempSpace = new BitmapData(minW, minH, true, 0x0); + } + if (tempSpace.width < minW || tempSpace.height < minH) + { + tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); + } + + var r:Rectangle = new Rectangle(); + + baseBounds.left = Math.floor(baseBounds.left); + baseBounds.right = Math.ceil(baseBounds.right); + + baseBounds.top = Math.floor(baseBounds.top); + baseBounds.bottom = Math.ceil(baseBounds.bottom); + + var i; + + var needsChecking = true; + while (needsChecking) + { + needsChecking = false; + r.left = baseBounds.left - padAmount; + r.right = baseBounds.right + padAmount; + + r.top = baseBounds.top - padAmount; + r.bottom = baseBounds.bottom + padAmount; + + ret = r.clone(); + + tempSpaceRect.x = tempSpaceRect.y = 0; + tempSpaceRect.width = tempSpace.width; + tempSpaceRect.height = tempSpace.height; + tempSpace.fillRect(tempSpaceRect, 0x0); + + tempSpaceMatrix.identity(); + if (useMatrix) + { + tempSpaceMatrix.a = useMatrix.a; + tempSpaceMatrix.b = useMatrix.b; + tempSpaceMatrix.c = useMatrix.c; + tempSpaceMatrix.d = useMatrix.d; + tempSpaceMatrix.tx = useMatrix.tx; + tempSpaceMatrix.ty = useMatrix.ty; + } + tempSpaceMatrix.translate(-r.left, -r.top); + + lastDrawOffset.x = -r.left; + lastDrawOffset.y = -r.top; + tempSpace.draw(clip, tempSpaceMatrix); + + tempSpaceRect.width = 1; + tempSpaceRect.height = r.height; + + var sideMovedIn = 0; + for (i = 0; i < r.width; i++) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.left++; + sideMovedIn++; + } + } + if (ret.left < baseBounds.left - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.width - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.right--; + } + } + if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + sideMovedIn = 0; + tempSpaceRect.width = r.width; + tempSpaceRect.height = 1; + tempSpaceRect.x = 0; + for (i = 0; i < r.height; i++) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.top++; + sideMovedIn++; + } + } + if (ret.top < baseBounds.top - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.height - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.bottom--; + } + } + if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + } + return ret; + } + + public static function TransformAABBRect(r:Rectangle, m:Matrix) + { + var o1X = r.left; + var o1Y = r.top; + + var o2X = r.right; + var o2Y = r.top; + + var o3X = r.left; + var o3Y = r.bottom; + + var o4X = r.right; + var o4Y = r.bottom; + + var n1X = o1X * m.a + o1Y * m.c + m.tx; + var n1Y = o1X * m.b + o1Y * m.d + m.ty; + + var n2X = o2X * m.a + o2Y * m.c + m.tx; + var n2Y = o2X * m.b + o2Y * m.d + m.ty; + + var n3X = o3X * m.a + o3Y * m.c + m.tx; + var n3Y = o3X * m.b + o3Y * m.d + m.ty; + + var n4X = o4X * m.a + o4Y * m.c + m.tx; + var n4Y = o4X * m.b + o4Y * m.d + m.ty; + + r.left = Math.min(n1X, n2X, n3X, n4X); + r.right = Math.max(n1X, n2X, n3X, n4X); + + r.top = Math.min(n1Y, n2Y, n3Y, n4Y); + r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); + } + } +} diff --git a/job.py b/job.py index 989c991..77c09e8 100644 --- a/job.py +++ b/job.py @@ -3,6 +3,7 @@ import json from validate import * from args import * +import copy asset_src_schema = { "type":"object", @@ -69,19 +70,24 @@ base_path = os.path.join(self.out_dir, self.rel_path) if not os.path.exists(base_path): os.makedirs(base_path) + resource_names = [] for i,r in enumerate(resources): - path = os.path.join(base_path, "%s_%04d.png" % (self.name, i)) + resource_name = "%s_%04d.png" % (self.name, i) if len(resources) > 1 else self.name + ".png" + resource_names.append(resource_name) + path = os.path.join(base_path, resource_name) with open(path, "wb") as f: f.write(base64.b64decode(r)) if len(data) == 1: graphic_and_asset = {} (name, graphic_data) = data.items()[0] - graphic_and_asset = {"data":graphic_data} + graphic_and_asset = {"data":graphic_data, "resources":resource_names} with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps(graphic_and_asset)) else: + write_data = copy.deepcopy(data) + write_data["resources"] = resource_names with open(os.path.join(base_path, self.name + ".asset"), "w") as f: - f.write(pretty_dumps(data)) + f.write(pretty_dumps(write_data)) for name,details in data.iteritems(): with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps({"data":self.name + ".asset"})) diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/flash/util/RectangleNode.as b/flash/util/RectangleNode.as new file mode 100644 index 0000000..6f31e44 --- /dev/null +++ b/flash/util/RectangleNode.as @@ -0,0 +1,178 @@ +package util { + import flash.geom.Rectangle; + + public class RectangleNode + { + public var Left:RectangleNode = null; + public var Right:RectangleNode = null; + public var Rect:Rectangle = null; + public var InUse:Boolean = false; + public var Removed:Boolean = false; + public var Parent:RectangleNode = null; + public var AllocationID = 0; + public var Host:RectanglePacker= null; + public var MinAllocationID = 0; + public var NodeID; + public static var NextNodeID = 0; + + public var DontRemove = false; + + public var LastAccessTime = 0; + + public var Flags = []; + + public var UpdateTo:RectangleNode = null; + + /* + public function get Removed() + { + return _Removed; + } + + public function set Removed(r) + { + this._Removed = r; + } + + public function get Host():RectanglePacker + { + return _Host; + } + public function set Host(p:RectanglePacker) + { + this._Host = p; + + if (_Left && _Left.Host != p) + { + throw new Error("bad left host"); + } + if (_Right && _Right.Host != p) + { + throw new Error("bad right host"); + } + if (_Parent && _Parent.Host != p) + { + throw new Error("bad parent host"); + } + + } + + public function get Left():RectangleNode + { + return _Left; + } + public function set Left(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad left host"); + } + _Left = n; + } + public function get Right():RectangleNode + { + return _Right; + } + public function set Right(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad right host"); + } + _Right = n; + } + + public function get Parent():RectangleNode + { + return _Parent; + } + public function set Parent(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad parent host"); + } + _Parent = n; + } + */ + public function get IsFreeSpace() + { + return Left == null && Right == null && !InUse; + } + public function UpdateLinksFromNode(node:RectangleNode) + { + if (node.Parent) + { + if (node.Parent.Left == node) + { + node.Parent.Left = this; + } + if (node.Parent.Right == node) + { + node.Parent.Right = this; + } + } + if (node.Left) + { + node.Left.Parent = this; + } + if (node.Right) + { + node.Right.Parent = this; + } + } + public function MakeFromNode(node:RectangleNode) + { + //_Host = node.Host; + Host = node.Host; + Left = node.Left; + Right = node.Right; + Parent = node.Parent; + AllocationID = node.AllocationID; + InUse = node.InUse; + MinAllocationID = node.MinAllocationID; + NodeID = node.NodeID; + Rect = node.Rect.clone(); + Removed = node.Removed; + DontRemove = node.DontRemove; + } + public function RectangleNode(x, y, w, h, host:RectanglePacker) + { + this.NodeID = NextNodeID++; + this.Host = host; + this.Rect = new Rectangle(x, y, w, h); + } + public function OutputJSON() + { + var node = {}; + node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; + node.in_use = InUse; + node.id = NodeID; + if (this.Left) node.left = this.Left.OutputJSON(); + if (this.Right) node.right = this.Right.OutputJSON(); + return node; + } + + public function ReadJSON(details) + { + details.new_node = this; + this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); + this.Removed = false; + + this.InUse = details.in_use; + + if (details.hasOwnProperty("right")) + { + this.Right = new RectangleNode(0, 0, 0, 0, this.Host); + Right.ReadJSON(details.right); + Right.Parent = this; + } + if (details.hasOwnProperty("left")) + { + this.Left = new RectangleNode(0, 0, 0, 0, this.Host); + Left.ReadJSON(details.left); + Left.Parent = this; + } + } + } +} diff --git a/flash/util/RectanglePacker.as b/flash/util/RectanglePacker.as new file mode 100644 index 0000000..597d7fd --- /dev/null +++ b/flash/util/RectanglePacker.as @@ -0,0 +1,562 @@ +package util { + import flash.geom.*; + import flash.display.BitmapData; + import flash.display.MovieClip; + import flash.text.TextField; + import flash.events.*; + import flash.sampler.StackFrame; + + public class RectanglePacker + { + protected var w:int; + protected var h:int; + protected var root:RectangleNode; + public var NextAllocationID = 0; + + public function get width():int { return w; } + public function get height():int { return h; } + + public function RectanglePacker(w, h) + { + this.w = w; + this.h = h; + root = new RectangleNode(0, 0, w, h, this); + root.AllocationID = -1; + } + protected var area = 0; + + protected var testRender:MovieClip = new MovieClip(); + + public function GetRoot():RectangleNode + { + return root; + } + + public function GetLeafNodes():Array + { + return GetLeafNodesInternal(root); + } + + protected function GetLeafNodesInternal(n:RectangleNode):Array + { + if (n.InUse) return [n]; + var ret:Array = new Array(); + if (n.Left) ret = GetLeafNodesInternal(n.Left); + if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); + return ret; + } + + public function GetUsedArea() + { + return area; + } + + public function get efficiency() + { + return area / (w * h); + } + + protected function RectCost(w, h) + { + if (w == 0 || h == 0) return 99999999; + return (Math.max(w, h) / Math.min(w, h)) * w * h; + } + + protected function EnumerateTree(r:RectangleNode = null, indent = "") + { + if (r == null) r = this.root; + var str = ""; + str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; + if (r.Left) str += EnumerateTree(r.Left, indent + " "); + if (r.Right) str += EnumerateTree(r.Left, indent + " "); + return str; + } + + /* + * Remove a list of nodes from the tree. + * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree + * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, + leaving the original objects intact (in case something still references them) + */ + public function RemoveNodes(nodes:Array, fullyDestroy = true) + { + + /* DEBUG CHECKS */ + /* + this.PerformDebugCheck(); + + var str = ""; + for (var i = 0; i < nodes.length; i++) + { + str += nodes[i].NodeID + "\n"; + } + + var orig = nodes.concat(); + + var strs = [str, EnumerateTree()]; + + RenderDetailsBox.StartTrack("PackRemoveTime"); + + for (var i = 0; i < nodes.length; i++) + { + var n:RectangleNode = nodes[i]; + if (n.Host != this) + { + throw new Error("bad host!"); + } + } + */ + /* END DEBUG CHECKS */ + + var i, n:RectangleNode, p:RectangleNode; + + // setup the Removed flag on every node that should be removed + // we also check at this time to see if any more nodes need to be removed, such as a parent of + // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + if (n.Host == this) + { + n.Removed = true; + + if (n.InUse) + { + // sum up the total removed area + area -= n.Rect.width * n.Rect.height; + } + + if (n.Parent != null) + { + p = n.Parent; + // check and see if the current node's parent still has any valid children + if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) + { + // all of the current nodes siblings are either being removed or are blank, so + // we can remove the parent too + if (p.Left.IsFreeSpace) + { + // the left child was empty space before, so we can remove it (if it wasn't + // empty space it is already being removed so it doesn't need to be added + // to the list) + if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); + } + if (p.Right.IsFreeSpace) + { + // the right child was empty space before, so we can remove it + if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); + } + if (p != root && nodes.indexOf(p) == -1) + { + // remove the parent node too (provided it isn't the root!) + nodes.push(p); + } + } + } + } + } + + // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, + // so go ahead and remove them + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + + if (n.Parent != null) + { + // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not + // also getting removed!) + p = n.Parent; + + if (!p.Removed) + { + if (p.Left && p.Right) + { + var newNode:RectangleNode; + if (p.Left.Removed && p.Right.Removed) + { + // both children were removed, but the parent wasn't, so the parent must be root + // (since we never remove the root) + if (p != root) + { + throw new Error("should be root"); + } + p.Left.Parent = null; + p.Right.Parent = null; + p.Left = null; + p.Right = null; + p.InUse = false; + } else if (!p.Left.Removed) { + // Right node removed, Left node not removed + if (!p.Left.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Right); + newNode.UpdateLinksFromNode(p.Right); + } + // Left node is used + p.Right.InUse = false; + p.Right.Left = null; + p.Right.Right = null; + p.Right.Removed = false; + } else { + throw new Error("should have been caught above!"); + } + } else { + // Left node removed, Right node not removed + if (!p.Right.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Left); + newNode.UpdateLinksFromNode(p.Left); + } + // Left node is used + //p.Left.Removed = true; + p.Left.InUse = false; + p.Left.Left = null; + p.Left.Right = null; + p.Left.Removed = false; + //p.Left.Parent = null; + } else { + throw new Error("should have been caught above!"); + } + } + } else { + // huh? how does n.Parent == p but p has no children? something went wrong + throw new Error("shouldn't have gotten here"); + } + } + } + //strs.push(EnumerateTree()); + } + } + + public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode + { + + var node:RectangleNode = FindSizedNode(w, h, root); + + if (node == null) + { + //UHOH, texture full + return null; + } + area += w * h; + node.InUse = true; + + var splitVertFirstCost = 0; + if (w < node.Rect.width) + { + splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); + } + + var splitHorizFirstCost = 0; + if (h < node.Rect.height) + { + splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); + } + + + + if (splitVertFirstCost <= splitHorizFirstCost) + { + node.Flags.push("SplitVertFirst"); + if (w < node.Rect.width) + { + node.Flags.push("SplitVert"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + if (h < node.Rect.height) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + } else { + node.Flags.push("SplitHorzFirst"); + if (h < node.Rect.height) + { + node.Flags.push("SplitVert"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + if (w < node.Rect.width) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + } + NextAllocationID++; + if (useInstead) + { + useInstead.MakeFromNode(node); + useInstead.UpdateLinksFromNode(node); + useInstead.Flags = node.Flags; + node = useInstead; + node.Flags.push("UseInstead"); + } + + //if (!CheckOKNode(node)) node.Flags.push("BadNode"); + + return node; + } + public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) + { + if (r == null) r = this.root; + if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) + { + var ancestor:RectangleNode = FindCommonNode(n, r); + throw new Error("bad node allocated!"); + return false; + } + var ok = true; + if (r.Left) ok = ok && CheckOKNode(n, r.Left); + if (r.Right) ok = ok && CheckOKNode(n, r.Right); + return ok; + } + + public function PerformDebugCheck() + { + DebugInternal(this.root); + } + + protected function DebugInternal(n:RectangleNode) + { + if (n.Host != this) + { + throw new Error("problem with host!"); + } + if (n.IsFreeSpace) + { + if (n.Left || n.Right) + { + throw new Error("shouldn't have children"); + } + } + if ((n.Left && !n.Right) || (n.Right && !n.Left)) + { + throw new Error("mismatched children"); + } + if (n.Left && n.Left.Parent != n) + { + throw new Error("left child has bad parent"); + } + if (n.Right && n.Right.Parent != n) + { + throw new Error("right child has bad parent"); + } + if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) + { + throw new Error("problem with parent"); + } + if (n.Left) DebugInternal(n.Left); + if (n.Right) DebugInternal(n.Right); + } + + public function FindCommonNode(a:RectangleNode, b:RectangleNode) + { + var aHistory = []; + var bHistory = []; + while (a != null) + { + aHistory.push(a); + a = a.Parent; + } + while (b != null) + { + bHistory.push(b); + b = b.Parent; + } + var i = aHistory.length - 1; + var j = bHistory.length - 1; + var same = null; + while (i >= 0 && j >= 0) + { + if (aHistory[i] == bHistory[j]) + { + same = aHistory[i]; + } else { + break; + } + i--; + j--; + } + return same; + } + + public function TestRender() + { + while (testRender.numChildren > 0) + { + testRender.removeChildAt(0); + } + testRender.graphics.clear(); + TestRenderNode(root, testRender); + return testRender; + } + protected function TestRenderNode(n:RectangleNode, m:MovieClip) + { + var g:MovieClip = new MovieClip(); + m.addChild(g); + g.graphics.lineStyle(1, 0, 1); + if (n.Left != null) TestRenderNode(n.Left, m); + if (n.Left != null) TestRenderNode(n.Right, m); + if (n.InUse) + { + g.graphics.beginFill(0xFFFF00, 0.2); + } + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + if (n.InUse) + { + g.graphics.endFill(); + var t:TextField = new TextField(); + t.text = n.NodeID; + t.x = n.Rect.x + n.Rect.width / 2.0; + t.y = n.Rect.y + n.Rect.height / 2.0; + g.addChild(t); + g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); + g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); + } + + } + public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) + { + if (n.InUse) + { + //_trace(Math.round(n.LastAccessTime / 1000)); + } + var p:RectangleNode = n.Parent; + if (p) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); + g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); + g.graphics.endFill(); + t.text = p.NodeID; + if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); + g.oldListener = function(e){MouseOver(p, g, t);}; + g.addEventListener(MouseEvent.CLICK, g.oldListener); + } + } + public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(0xFFFF00, 0.2); + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + g.graphics.endFill(); + t.text = n.NodeID; + } + protected function SplitVert(node:RectangleNode, leftWidth) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function SplitHoriz(node:RectangleNode, topHeight) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode + { + if (node.InUse) return null; + if (node.Rect.width >= w && node.Rect.height >= h) + { + if (node.Left != null && node.Right != null) + { + var t:RectangleNode = FindSizedNode(w, h, node.Left); + if (t != null) return t; + t = FindSizedNode(w, h, node.Right); + return t; + } else { + return node; + } + } + return null; + } + + public function LoadTree(details) + { + this.root = new RectangleNode(0, 0, 0, 0, this); + root.ReadJSON(details); + + this.NextAllocationID = 0; + this.area = 0; + + var queue:Array = new Array(); + queue.push(root); + while (queue.length > 0) + { + var node:RectangleNode = queue.shift(); + node.AllocationID = NextAllocationID; + node.MinAllocationID = NextAllocationID; + if (node.Left) queue.push(node.Left); + if (node.Right) queue.push(node.Right); + if (node.InUse) this.area += node.Rect.width * node.Rect.height; + } + NextAllocationID++; + } + + public function GetNodePath(node:RectangleNode) + { + var output:String = ""; + while (node != this.root) + { + output = (node == node.Parent.Left ? "l" : "r") + output; + node = node.Parent; + } + return output; + } + + public function GetNodeFromPath(path:String):RectangleNode + { + var node:RectangleNode = this.root; + for (var i = 0; i < path.length; i++) + { + if (!node) return null; + if (path.charAt(i) == "r") + { + node = node.Right; + } else { + node = node.Left; + } + } + return node; + } + } +} diff --git a/flash/util/Utils.as b/flash/util/Utils.as new file mode 100644 index 0000000..f792003 --- /dev/null +++ b/flash/util/Utils.as @@ -0,0 +1,389 @@ +package util +{ + import flash.display.*; + import flash.geom.*; + public class Utils + { + public static function GetChildren(clip:MovieClip):Array + { + var ret:Array = []; + for (var i = 0; i < clip.numChildren; i++) + { + ret.push(clip.getChildAt(i)); + } + return ret; + } + + /* + * angle difference + * (range -Math.PI to Math.PI) + */ + public static function GetAngleDiff(a, b) + { + var angleDiff = b - a; + + while (angleDiff > Math.PI) + { + angleDiff -= Math.PI * 2; + } + while (angleDiff < -Math.PI) + { + angleDiff += Math.PI * 2; + } + return angleDiff; + } + + /* + * angle difference + * (range 0 to Math.PI) + */ + public static function GetAngleDiffAbs(a, b) + { + var angleDiff = GetAngleDiff(a, b); + while (angleDiff < 0) + { + angleDiff += Math.PI * 2; + } + + if (angleDiff > Math.PI) + { + angleDiff = Math.PI * 2 - angleDiff; + } + + return angleDiff; + } + + public static function GetTransform(from:Matrix, to:Matrix) + { + var i:Matrix = from.clone(); + i.invert(); + var m:Matrix = to.clone(); + m.concat(i); + return m; + } + + public static function Decompose(m:Matrix) + { + var s:Point = ScaleFromMat(m); + m = m.clone(); + + var sxUnit = s.x >= 0 ? 1 : -1; + var syUnit = s.y >= 0 ? 1 : -1; + + m.scale(sxUnit, syUnit); + + //m.a /= sxUnit; + //m.d /= syUnit; + var rot = RotFromMat(m); + return {sx:s.x, sy:s.y, rot:rot}; + } + + public static function RotFromMat(m:Matrix) + { + return Math.atan2(-m.c, m.a); + } + + public static function ScaleFromMat(m:Matrix):Point + { + var xAxisX = m.a; + var xAxisY = m.c; + + var yAxisX = m.b; + var yAxisY = m.d; + + var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); + if (m.a < 0) sx *= -1; + + var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); + if (m.d < 0) sy *= -1; + + return new Point(sx, sy); + } + + public static function TransformRect(r:Rectangle, m:Matrix) + { + var p1:Point = new Point(r.left, r.top); + var p2:Point = new Point(r.right, r.top); + var p3:Point = new Point(r.left, r.bottom); + var p4:Point = new Point(r.right, r.bottom); + + p1 = m.transformPoint(p1); + p2 = m.transformPoint(p2); + p3 = m.transformPoint(p3); + p4 = m.transformPoint(p4); + + r.left = Math.min(p1.x, p2.x, p3.x, p4.x); + r.top = Math.min(p1.y, p2.y, p3.y, p4.y); + r.right = Math.max(p1.x, p2.x, p3.x, p4.x); + r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); + } + + public static function RoundRect(r:Rectangle) + { + r.left = Math.floor(r.left); + r.top = Math.floor(r.top); + r.right = Math.ceil(r.right); + r.bottom = Math.ceil(r.bottom); + } + + public static function ScaleRect(r:Rectangle, s) + { + r.left *= s; + r.top *= s; + r.right *= s; + r.bottom *= s; + } + + public static function RecursivelyStop(clip) + { + if (clip is MovieClip) + { + clip.stop(); + } + if (clip is DisplayObjectContainer) + { + for (var i = 0; i < clip.numChildren; i++) + { + RecursivelyStop(clip.getChildAt(i)); + } + } + } + + public static function WeirdGotoFrame(clip:MovieClip, frame) + { + var dir = clip.currentFrame > frame ? -1 : 1; + while (clip.currentFrame != frame) + { + RecurseDir(clip, dir); + } + } + + protected static function RecurseDir(clip:MovieClip, dir) + { + for (var i = 0; i < clip.numChildren; i++) + { + var child = clip.getChildAt(i); + if (child is MovieClip) + { + RecurseDir(child, dir); + } + } + if (dir == 1) + { + clip.nextFrame(); + } else { + clip.prevFrame(); + } + } + + protected static var tempSpace:BitmapData = null; + protected static var tempSpaceRect:Rectangle = new Rectangle(); + protected static var tempSpaceMatrix:Matrix = new Matrix(); + protected static var tempSpaceZero:Point = new Point(); + protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); + protected static var lastDrawOffset:Point = new Point(); + public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle + { + if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); + + var oldPad = 0; + var padAmount = 5; + + var ret:Rectangle = new Rectangle(); + + var baseBounds:Rectangle = clip.getBounds(clip); + + var boundsClip:DisplayObject = null; + if (clip is DisplayObjectContainer) + { + boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); + } + + if (boundsClip != null) + { + baseBounds = boundsClip.getBounds(clip); + } + + if (useMatrix) + { + TransformAABBRect(baseBounds, useMatrix); + } + + if (boundsClip != null) + { + return baseBounds; + } + + var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); + var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); + if (tempSpace == null) + { + tempSpace = new BitmapData(minW, minH, true, 0x0); + } + if (tempSpace.width < minW || tempSpace.height < minH) + { + tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); + } + + var r:Rectangle = new Rectangle(); + + baseBounds.left = Math.floor(baseBounds.left); + baseBounds.right = Math.ceil(baseBounds.right); + + baseBounds.top = Math.floor(baseBounds.top); + baseBounds.bottom = Math.ceil(baseBounds.bottom); + + var i; + + var needsChecking = true; + while (needsChecking) + { + needsChecking = false; + r.left = baseBounds.left - padAmount; + r.right = baseBounds.right + padAmount; + + r.top = baseBounds.top - padAmount; + r.bottom = baseBounds.bottom + padAmount; + + ret = r.clone(); + + tempSpaceRect.x = tempSpaceRect.y = 0; + tempSpaceRect.width = tempSpace.width; + tempSpaceRect.height = tempSpace.height; + tempSpace.fillRect(tempSpaceRect, 0x0); + + tempSpaceMatrix.identity(); + if (useMatrix) + { + tempSpaceMatrix.a = useMatrix.a; + tempSpaceMatrix.b = useMatrix.b; + tempSpaceMatrix.c = useMatrix.c; + tempSpaceMatrix.d = useMatrix.d; + tempSpaceMatrix.tx = useMatrix.tx; + tempSpaceMatrix.ty = useMatrix.ty; + } + tempSpaceMatrix.translate(-r.left, -r.top); + + lastDrawOffset.x = -r.left; + lastDrawOffset.y = -r.top; + tempSpace.draw(clip, tempSpaceMatrix); + + tempSpaceRect.width = 1; + tempSpaceRect.height = r.height; + + var sideMovedIn = 0; + for (i = 0; i < r.width; i++) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.left++; + sideMovedIn++; + } + } + if (ret.left < baseBounds.left - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.width - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.right--; + } + } + if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + sideMovedIn = 0; + tempSpaceRect.width = r.width; + tempSpaceRect.height = 1; + tempSpaceRect.x = 0; + for (i = 0; i < r.height; i++) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.top++; + sideMovedIn++; + } + } + if (ret.top < baseBounds.top - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.height - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.bottom--; + } + } + if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + } + return ret; + } + + public static function TransformAABBRect(r:Rectangle, m:Matrix) + { + var o1X = r.left; + var o1Y = r.top; + + var o2X = r.right; + var o2Y = r.top; + + var o3X = r.left; + var o3Y = r.bottom; + + var o4X = r.right; + var o4Y = r.bottom; + + var n1X = o1X * m.a + o1Y * m.c + m.tx; + var n1Y = o1X * m.b + o1Y * m.d + m.ty; + + var n2X = o2X * m.a + o2Y * m.c + m.tx; + var n2Y = o2X * m.b + o2Y * m.d + m.ty; + + var n3X = o3X * m.a + o3Y * m.c + m.tx; + var n3Y = o3X * m.b + o3Y * m.d + m.ty; + + var n4X = o4X * m.a + o4Y * m.c + m.tx; + var n4Y = o4X * m.b + o4Y * m.d + m.ty; + + r.left = Math.min(n1X, n2X, n3X, n4X); + r.right = Math.max(n1X, n2X, n3X, n4X); + + r.top = Math.min(n1Y, n2Y, n3Y, n4Y); + r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); + } + } +} diff --git a/job.py b/job.py index 989c991..77c09e8 100644 --- a/job.py +++ b/job.py @@ -3,6 +3,7 @@ import json from validate import * from args import * +import copy asset_src_schema = { "type":"object", @@ -69,19 +70,24 @@ base_path = os.path.join(self.out_dir, self.rel_path) if not os.path.exists(base_path): os.makedirs(base_path) + resource_names = [] for i,r in enumerate(resources): - path = os.path.join(base_path, "%s_%04d.png" % (self.name, i)) + resource_name = "%s_%04d.png" % (self.name, i) if len(resources) > 1 else self.name + ".png" + resource_names.append(resource_name) + path = os.path.join(base_path, resource_name) with open(path, "wb") as f: f.write(base64.b64decode(r)) if len(data) == 1: graphic_and_asset = {} (name, graphic_data) = data.items()[0] - graphic_and_asset = {"data":graphic_data} + graphic_and_asset = {"data":graphic_data, "resources":resource_names} with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps(graphic_and_asset)) else: + write_data = copy.deepcopy(data) + write_data["resources"] = resource_names with open(os.path.join(base_path, self.name + ".asset"), "w") as f: - f.write(pretty_dumps(data)) + f.write(pretty_dumps(write_data)) for name,details in data.iteritems(): with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps({"data":self.name + ".asset"})) diff --git a/old/Checkbox.as b/old/Checkbox.as deleted file mode 100644 index c5aaba2..0000000 --- a/old/Checkbox.as +++ /dev/null @@ -1,42 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - - public class Checkbox extends MovieClip - { - public var Enabled:Boolean = true; - public function Checkbox() - { - checkbox.gotoAndStop(1); - checkbox.addEventListener(MouseEvent.CLICK, Clicked); - } - - protected function Clicked(event) - { - if (!Enabled) return; - Toggle(); - if (OnClick != null) OnClick(OnClickParam); - } - - protected var checked = false; - public function set Checked(value) { checked = value; checkbox.gotoAndStop(checked ? 2 : 1); } - public function get Checked() { return checked; } - - public function set Text(value) { text.text = value; } - - public var OnClickParam; - public var OnClick; - - - public function Toggle() - { - checked = !checked; - checkbox.gotoAndStop(checked ? 2 : 1); - - - } - - } - -} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/flash/util/RectangleNode.as b/flash/util/RectangleNode.as new file mode 100644 index 0000000..6f31e44 --- /dev/null +++ b/flash/util/RectangleNode.as @@ -0,0 +1,178 @@ +package util { + import flash.geom.Rectangle; + + public class RectangleNode + { + public var Left:RectangleNode = null; + public var Right:RectangleNode = null; + public var Rect:Rectangle = null; + public var InUse:Boolean = false; + public var Removed:Boolean = false; + public var Parent:RectangleNode = null; + public var AllocationID = 0; + public var Host:RectanglePacker= null; + public var MinAllocationID = 0; + public var NodeID; + public static var NextNodeID = 0; + + public var DontRemove = false; + + public var LastAccessTime = 0; + + public var Flags = []; + + public var UpdateTo:RectangleNode = null; + + /* + public function get Removed() + { + return _Removed; + } + + public function set Removed(r) + { + this._Removed = r; + } + + public function get Host():RectanglePacker + { + return _Host; + } + public function set Host(p:RectanglePacker) + { + this._Host = p; + + if (_Left && _Left.Host != p) + { + throw new Error("bad left host"); + } + if (_Right && _Right.Host != p) + { + throw new Error("bad right host"); + } + if (_Parent && _Parent.Host != p) + { + throw new Error("bad parent host"); + } + + } + + public function get Left():RectangleNode + { + return _Left; + } + public function set Left(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad left host"); + } + _Left = n; + } + public function get Right():RectangleNode + { + return _Right; + } + public function set Right(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad right host"); + } + _Right = n; + } + + public function get Parent():RectangleNode + { + return _Parent; + } + public function set Parent(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad parent host"); + } + _Parent = n; + } + */ + public function get IsFreeSpace() + { + return Left == null && Right == null && !InUse; + } + public function UpdateLinksFromNode(node:RectangleNode) + { + if (node.Parent) + { + if (node.Parent.Left == node) + { + node.Parent.Left = this; + } + if (node.Parent.Right == node) + { + node.Parent.Right = this; + } + } + if (node.Left) + { + node.Left.Parent = this; + } + if (node.Right) + { + node.Right.Parent = this; + } + } + public function MakeFromNode(node:RectangleNode) + { + //_Host = node.Host; + Host = node.Host; + Left = node.Left; + Right = node.Right; + Parent = node.Parent; + AllocationID = node.AllocationID; + InUse = node.InUse; + MinAllocationID = node.MinAllocationID; + NodeID = node.NodeID; + Rect = node.Rect.clone(); + Removed = node.Removed; + DontRemove = node.DontRemove; + } + public function RectangleNode(x, y, w, h, host:RectanglePacker) + { + this.NodeID = NextNodeID++; + this.Host = host; + this.Rect = new Rectangle(x, y, w, h); + } + public function OutputJSON() + { + var node = {}; + node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; + node.in_use = InUse; + node.id = NodeID; + if (this.Left) node.left = this.Left.OutputJSON(); + if (this.Right) node.right = this.Right.OutputJSON(); + return node; + } + + public function ReadJSON(details) + { + details.new_node = this; + this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); + this.Removed = false; + + this.InUse = details.in_use; + + if (details.hasOwnProperty("right")) + { + this.Right = new RectangleNode(0, 0, 0, 0, this.Host); + Right.ReadJSON(details.right); + Right.Parent = this; + } + if (details.hasOwnProperty("left")) + { + this.Left = new RectangleNode(0, 0, 0, 0, this.Host); + Left.ReadJSON(details.left); + Left.Parent = this; + } + } + } +} diff --git a/flash/util/RectanglePacker.as b/flash/util/RectanglePacker.as new file mode 100644 index 0000000..597d7fd --- /dev/null +++ b/flash/util/RectanglePacker.as @@ -0,0 +1,562 @@ +package util { + import flash.geom.*; + import flash.display.BitmapData; + import flash.display.MovieClip; + import flash.text.TextField; + import flash.events.*; + import flash.sampler.StackFrame; + + public class RectanglePacker + { + protected var w:int; + protected var h:int; + protected var root:RectangleNode; + public var NextAllocationID = 0; + + public function get width():int { return w; } + public function get height():int { return h; } + + public function RectanglePacker(w, h) + { + this.w = w; + this.h = h; + root = new RectangleNode(0, 0, w, h, this); + root.AllocationID = -1; + } + protected var area = 0; + + protected var testRender:MovieClip = new MovieClip(); + + public function GetRoot():RectangleNode + { + return root; + } + + public function GetLeafNodes():Array + { + return GetLeafNodesInternal(root); + } + + protected function GetLeafNodesInternal(n:RectangleNode):Array + { + if (n.InUse) return [n]; + var ret:Array = new Array(); + if (n.Left) ret = GetLeafNodesInternal(n.Left); + if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); + return ret; + } + + public function GetUsedArea() + { + return area; + } + + public function get efficiency() + { + return area / (w * h); + } + + protected function RectCost(w, h) + { + if (w == 0 || h == 0) return 99999999; + return (Math.max(w, h) / Math.min(w, h)) * w * h; + } + + protected function EnumerateTree(r:RectangleNode = null, indent = "") + { + if (r == null) r = this.root; + var str = ""; + str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; + if (r.Left) str += EnumerateTree(r.Left, indent + " "); + if (r.Right) str += EnumerateTree(r.Left, indent + " "); + return str; + } + + /* + * Remove a list of nodes from the tree. + * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree + * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, + leaving the original objects intact (in case something still references them) + */ + public function RemoveNodes(nodes:Array, fullyDestroy = true) + { + + /* DEBUG CHECKS */ + /* + this.PerformDebugCheck(); + + var str = ""; + for (var i = 0; i < nodes.length; i++) + { + str += nodes[i].NodeID + "\n"; + } + + var orig = nodes.concat(); + + var strs = [str, EnumerateTree()]; + + RenderDetailsBox.StartTrack("PackRemoveTime"); + + for (var i = 0; i < nodes.length; i++) + { + var n:RectangleNode = nodes[i]; + if (n.Host != this) + { + throw new Error("bad host!"); + } + } + */ + /* END DEBUG CHECKS */ + + var i, n:RectangleNode, p:RectangleNode; + + // setup the Removed flag on every node that should be removed + // we also check at this time to see if any more nodes need to be removed, such as a parent of + // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + if (n.Host == this) + { + n.Removed = true; + + if (n.InUse) + { + // sum up the total removed area + area -= n.Rect.width * n.Rect.height; + } + + if (n.Parent != null) + { + p = n.Parent; + // check and see if the current node's parent still has any valid children + if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) + { + // all of the current nodes siblings are either being removed or are blank, so + // we can remove the parent too + if (p.Left.IsFreeSpace) + { + // the left child was empty space before, so we can remove it (if it wasn't + // empty space it is already being removed so it doesn't need to be added + // to the list) + if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); + } + if (p.Right.IsFreeSpace) + { + // the right child was empty space before, so we can remove it + if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); + } + if (p != root && nodes.indexOf(p) == -1) + { + // remove the parent node too (provided it isn't the root!) + nodes.push(p); + } + } + } + } + } + + // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, + // so go ahead and remove them + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + + if (n.Parent != null) + { + // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not + // also getting removed!) + p = n.Parent; + + if (!p.Removed) + { + if (p.Left && p.Right) + { + var newNode:RectangleNode; + if (p.Left.Removed && p.Right.Removed) + { + // both children were removed, but the parent wasn't, so the parent must be root + // (since we never remove the root) + if (p != root) + { + throw new Error("should be root"); + } + p.Left.Parent = null; + p.Right.Parent = null; + p.Left = null; + p.Right = null; + p.InUse = false; + } else if (!p.Left.Removed) { + // Right node removed, Left node not removed + if (!p.Left.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Right); + newNode.UpdateLinksFromNode(p.Right); + } + // Left node is used + p.Right.InUse = false; + p.Right.Left = null; + p.Right.Right = null; + p.Right.Removed = false; + } else { + throw new Error("should have been caught above!"); + } + } else { + // Left node removed, Right node not removed + if (!p.Right.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Left); + newNode.UpdateLinksFromNode(p.Left); + } + // Left node is used + //p.Left.Removed = true; + p.Left.InUse = false; + p.Left.Left = null; + p.Left.Right = null; + p.Left.Removed = false; + //p.Left.Parent = null; + } else { + throw new Error("should have been caught above!"); + } + } + } else { + // huh? how does n.Parent == p but p has no children? something went wrong + throw new Error("shouldn't have gotten here"); + } + } + } + //strs.push(EnumerateTree()); + } + } + + public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode + { + + var node:RectangleNode = FindSizedNode(w, h, root); + + if (node == null) + { + //UHOH, texture full + return null; + } + area += w * h; + node.InUse = true; + + var splitVertFirstCost = 0; + if (w < node.Rect.width) + { + splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); + } + + var splitHorizFirstCost = 0; + if (h < node.Rect.height) + { + splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); + } + + + + if (splitVertFirstCost <= splitHorizFirstCost) + { + node.Flags.push("SplitVertFirst"); + if (w < node.Rect.width) + { + node.Flags.push("SplitVert"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + if (h < node.Rect.height) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + } else { + node.Flags.push("SplitHorzFirst"); + if (h < node.Rect.height) + { + node.Flags.push("SplitVert"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + if (w < node.Rect.width) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + } + NextAllocationID++; + if (useInstead) + { + useInstead.MakeFromNode(node); + useInstead.UpdateLinksFromNode(node); + useInstead.Flags = node.Flags; + node = useInstead; + node.Flags.push("UseInstead"); + } + + //if (!CheckOKNode(node)) node.Flags.push("BadNode"); + + return node; + } + public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) + { + if (r == null) r = this.root; + if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) + { + var ancestor:RectangleNode = FindCommonNode(n, r); + throw new Error("bad node allocated!"); + return false; + } + var ok = true; + if (r.Left) ok = ok && CheckOKNode(n, r.Left); + if (r.Right) ok = ok && CheckOKNode(n, r.Right); + return ok; + } + + public function PerformDebugCheck() + { + DebugInternal(this.root); + } + + protected function DebugInternal(n:RectangleNode) + { + if (n.Host != this) + { + throw new Error("problem with host!"); + } + if (n.IsFreeSpace) + { + if (n.Left || n.Right) + { + throw new Error("shouldn't have children"); + } + } + if ((n.Left && !n.Right) || (n.Right && !n.Left)) + { + throw new Error("mismatched children"); + } + if (n.Left && n.Left.Parent != n) + { + throw new Error("left child has bad parent"); + } + if (n.Right && n.Right.Parent != n) + { + throw new Error("right child has bad parent"); + } + if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) + { + throw new Error("problem with parent"); + } + if (n.Left) DebugInternal(n.Left); + if (n.Right) DebugInternal(n.Right); + } + + public function FindCommonNode(a:RectangleNode, b:RectangleNode) + { + var aHistory = []; + var bHistory = []; + while (a != null) + { + aHistory.push(a); + a = a.Parent; + } + while (b != null) + { + bHistory.push(b); + b = b.Parent; + } + var i = aHistory.length - 1; + var j = bHistory.length - 1; + var same = null; + while (i >= 0 && j >= 0) + { + if (aHistory[i] == bHistory[j]) + { + same = aHistory[i]; + } else { + break; + } + i--; + j--; + } + return same; + } + + public function TestRender() + { + while (testRender.numChildren > 0) + { + testRender.removeChildAt(0); + } + testRender.graphics.clear(); + TestRenderNode(root, testRender); + return testRender; + } + protected function TestRenderNode(n:RectangleNode, m:MovieClip) + { + var g:MovieClip = new MovieClip(); + m.addChild(g); + g.graphics.lineStyle(1, 0, 1); + if (n.Left != null) TestRenderNode(n.Left, m); + if (n.Left != null) TestRenderNode(n.Right, m); + if (n.InUse) + { + g.graphics.beginFill(0xFFFF00, 0.2); + } + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + if (n.InUse) + { + g.graphics.endFill(); + var t:TextField = new TextField(); + t.text = n.NodeID; + t.x = n.Rect.x + n.Rect.width / 2.0; + t.y = n.Rect.y + n.Rect.height / 2.0; + g.addChild(t); + g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); + g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); + } + + } + public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) + { + if (n.InUse) + { + //_trace(Math.round(n.LastAccessTime / 1000)); + } + var p:RectangleNode = n.Parent; + if (p) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); + g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); + g.graphics.endFill(); + t.text = p.NodeID; + if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); + g.oldListener = function(e){MouseOver(p, g, t);}; + g.addEventListener(MouseEvent.CLICK, g.oldListener); + } + } + public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(0xFFFF00, 0.2); + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + g.graphics.endFill(); + t.text = n.NodeID; + } + protected function SplitVert(node:RectangleNode, leftWidth) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function SplitHoriz(node:RectangleNode, topHeight) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode + { + if (node.InUse) return null; + if (node.Rect.width >= w && node.Rect.height >= h) + { + if (node.Left != null && node.Right != null) + { + var t:RectangleNode = FindSizedNode(w, h, node.Left); + if (t != null) return t; + t = FindSizedNode(w, h, node.Right); + return t; + } else { + return node; + } + } + return null; + } + + public function LoadTree(details) + { + this.root = new RectangleNode(0, 0, 0, 0, this); + root.ReadJSON(details); + + this.NextAllocationID = 0; + this.area = 0; + + var queue:Array = new Array(); + queue.push(root); + while (queue.length > 0) + { + var node:RectangleNode = queue.shift(); + node.AllocationID = NextAllocationID; + node.MinAllocationID = NextAllocationID; + if (node.Left) queue.push(node.Left); + if (node.Right) queue.push(node.Right); + if (node.InUse) this.area += node.Rect.width * node.Rect.height; + } + NextAllocationID++; + } + + public function GetNodePath(node:RectangleNode) + { + var output:String = ""; + while (node != this.root) + { + output = (node == node.Parent.Left ? "l" : "r") + output; + node = node.Parent; + } + return output; + } + + public function GetNodeFromPath(path:String):RectangleNode + { + var node:RectangleNode = this.root; + for (var i = 0; i < path.length; i++) + { + if (!node) return null; + if (path.charAt(i) == "r") + { + node = node.Right; + } else { + node = node.Left; + } + } + return node; + } + } +} diff --git a/flash/util/Utils.as b/flash/util/Utils.as new file mode 100644 index 0000000..f792003 --- /dev/null +++ b/flash/util/Utils.as @@ -0,0 +1,389 @@ +package util +{ + import flash.display.*; + import flash.geom.*; + public class Utils + { + public static function GetChildren(clip:MovieClip):Array + { + var ret:Array = []; + for (var i = 0; i < clip.numChildren; i++) + { + ret.push(clip.getChildAt(i)); + } + return ret; + } + + /* + * angle difference + * (range -Math.PI to Math.PI) + */ + public static function GetAngleDiff(a, b) + { + var angleDiff = b - a; + + while (angleDiff > Math.PI) + { + angleDiff -= Math.PI * 2; + } + while (angleDiff < -Math.PI) + { + angleDiff += Math.PI * 2; + } + return angleDiff; + } + + /* + * angle difference + * (range 0 to Math.PI) + */ + public static function GetAngleDiffAbs(a, b) + { + var angleDiff = GetAngleDiff(a, b); + while (angleDiff < 0) + { + angleDiff += Math.PI * 2; + } + + if (angleDiff > Math.PI) + { + angleDiff = Math.PI * 2 - angleDiff; + } + + return angleDiff; + } + + public static function GetTransform(from:Matrix, to:Matrix) + { + var i:Matrix = from.clone(); + i.invert(); + var m:Matrix = to.clone(); + m.concat(i); + return m; + } + + public static function Decompose(m:Matrix) + { + var s:Point = ScaleFromMat(m); + m = m.clone(); + + var sxUnit = s.x >= 0 ? 1 : -1; + var syUnit = s.y >= 0 ? 1 : -1; + + m.scale(sxUnit, syUnit); + + //m.a /= sxUnit; + //m.d /= syUnit; + var rot = RotFromMat(m); + return {sx:s.x, sy:s.y, rot:rot}; + } + + public static function RotFromMat(m:Matrix) + { + return Math.atan2(-m.c, m.a); + } + + public static function ScaleFromMat(m:Matrix):Point + { + var xAxisX = m.a; + var xAxisY = m.c; + + var yAxisX = m.b; + var yAxisY = m.d; + + var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); + if (m.a < 0) sx *= -1; + + var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); + if (m.d < 0) sy *= -1; + + return new Point(sx, sy); + } + + public static function TransformRect(r:Rectangle, m:Matrix) + { + var p1:Point = new Point(r.left, r.top); + var p2:Point = new Point(r.right, r.top); + var p3:Point = new Point(r.left, r.bottom); + var p4:Point = new Point(r.right, r.bottom); + + p1 = m.transformPoint(p1); + p2 = m.transformPoint(p2); + p3 = m.transformPoint(p3); + p4 = m.transformPoint(p4); + + r.left = Math.min(p1.x, p2.x, p3.x, p4.x); + r.top = Math.min(p1.y, p2.y, p3.y, p4.y); + r.right = Math.max(p1.x, p2.x, p3.x, p4.x); + r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); + } + + public static function RoundRect(r:Rectangle) + { + r.left = Math.floor(r.left); + r.top = Math.floor(r.top); + r.right = Math.ceil(r.right); + r.bottom = Math.ceil(r.bottom); + } + + public static function ScaleRect(r:Rectangle, s) + { + r.left *= s; + r.top *= s; + r.right *= s; + r.bottom *= s; + } + + public static function RecursivelyStop(clip) + { + if (clip is MovieClip) + { + clip.stop(); + } + if (clip is DisplayObjectContainer) + { + for (var i = 0; i < clip.numChildren; i++) + { + RecursivelyStop(clip.getChildAt(i)); + } + } + } + + public static function WeirdGotoFrame(clip:MovieClip, frame) + { + var dir = clip.currentFrame > frame ? -1 : 1; + while (clip.currentFrame != frame) + { + RecurseDir(clip, dir); + } + } + + protected static function RecurseDir(clip:MovieClip, dir) + { + for (var i = 0; i < clip.numChildren; i++) + { + var child = clip.getChildAt(i); + if (child is MovieClip) + { + RecurseDir(child, dir); + } + } + if (dir == 1) + { + clip.nextFrame(); + } else { + clip.prevFrame(); + } + } + + protected static var tempSpace:BitmapData = null; + protected static var tempSpaceRect:Rectangle = new Rectangle(); + protected static var tempSpaceMatrix:Matrix = new Matrix(); + protected static var tempSpaceZero:Point = new Point(); + protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); + protected static var lastDrawOffset:Point = new Point(); + public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle + { + if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); + + var oldPad = 0; + var padAmount = 5; + + var ret:Rectangle = new Rectangle(); + + var baseBounds:Rectangle = clip.getBounds(clip); + + var boundsClip:DisplayObject = null; + if (clip is DisplayObjectContainer) + { + boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); + } + + if (boundsClip != null) + { + baseBounds = boundsClip.getBounds(clip); + } + + if (useMatrix) + { + TransformAABBRect(baseBounds, useMatrix); + } + + if (boundsClip != null) + { + return baseBounds; + } + + var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); + var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); + if (tempSpace == null) + { + tempSpace = new BitmapData(minW, minH, true, 0x0); + } + if (tempSpace.width < minW || tempSpace.height < minH) + { + tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); + } + + var r:Rectangle = new Rectangle(); + + baseBounds.left = Math.floor(baseBounds.left); + baseBounds.right = Math.ceil(baseBounds.right); + + baseBounds.top = Math.floor(baseBounds.top); + baseBounds.bottom = Math.ceil(baseBounds.bottom); + + var i; + + var needsChecking = true; + while (needsChecking) + { + needsChecking = false; + r.left = baseBounds.left - padAmount; + r.right = baseBounds.right + padAmount; + + r.top = baseBounds.top - padAmount; + r.bottom = baseBounds.bottom + padAmount; + + ret = r.clone(); + + tempSpaceRect.x = tempSpaceRect.y = 0; + tempSpaceRect.width = tempSpace.width; + tempSpaceRect.height = tempSpace.height; + tempSpace.fillRect(tempSpaceRect, 0x0); + + tempSpaceMatrix.identity(); + if (useMatrix) + { + tempSpaceMatrix.a = useMatrix.a; + tempSpaceMatrix.b = useMatrix.b; + tempSpaceMatrix.c = useMatrix.c; + tempSpaceMatrix.d = useMatrix.d; + tempSpaceMatrix.tx = useMatrix.tx; + tempSpaceMatrix.ty = useMatrix.ty; + } + tempSpaceMatrix.translate(-r.left, -r.top); + + lastDrawOffset.x = -r.left; + lastDrawOffset.y = -r.top; + tempSpace.draw(clip, tempSpaceMatrix); + + tempSpaceRect.width = 1; + tempSpaceRect.height = r.height; + + var sideMovedIn = 0; + for (i = 0; i < r.width; i++) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.left++; + sideMovedIn++; + } + } + if (ret.left < baseBounds.left - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.width - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.right--; + } + } + if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + sideMovedIn = 0; + tempSpaceRect.width = r.width; + tempSpaceRect.height = 1; + tempSpaceRect.x = 0; + for (i = 0; i < r.height; i++) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.top++; + sideMovedIn++; + } + } + if (ret.top < baseBounds.top - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.height - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.bottom--; + } + } + if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + } + return ret; + } + + public static function TransformAABBRect(r:Rectangle, m:Matrix) + { + var o1X = r.left; + var o1Y = r.top; + + var o2X = r.right; + var o2Y = r.top; + + var o3X = r.left; + var o3Y = r.bottom; + + var o4X = r.right; + var o4Y = r.bottom; + + var n1X = o1X * m.a + o1Y * m.c + m.tx; + var n1Y = o1X * m.b + o1Y * m.d + m.ty; + + var n2X = o2X * m.a + o2Y * m.c + m.tx; + var n2Y = o2X * m.b + o2Y * m.d + m.ty; + + var n3X = o3X * m.a + o3Y * m.c + m.tx; + var n3Y = o3X * m.b + o3Y * m.d + m.ty; + + var n4X = o4X * m.a + o4Y * m.c + m.tx; + var n4Y = o4X * m.b + o4Y * m.d + m.ty; + + r.left = Math.min(n1X, n2X, n3X, n4X); + r.right = Math.max(n1X, n2X, n3X, n4X); + + r.top = Math.min(n1Y, n2Y, n3Y, n4Y); + r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); + } + } +} diff --git a/job.py b/job.py index 989c991..77c09e8 100644 --- a/job.py +++ b/job.py @@ -3,6 +3,7 @@ import json from validate import * from args import * +import copy asset_src_schema = { "type":"object", @@ -69,19 +70,24 @@ base_path = os.path.join(self.out_dir, self.rel_path) if not os.path.exists(base_path): os.makedirs(base_path) + resource_names = [] for i,r in enumerate(resources): - path = os.path.join(base_path, "%s_%04d.png" % (self.name, i)) + resource_name = "%s_%04d.png" % (self.name, i) if len(resources) > 1 else self.name + ".png" + resource_names.append(resource_name) + path = os.path.join(base_path, resource_name) with open(path, "wb") as f: f.write(base64.b64decode(r)) if len(data) == 1: graphic_and_asset = {} (name, graphic_data) = data.items()[0] - graphic_and_asset = {"data":graphic_data} + graphic_and_asset = {"data":graphic_data, "resources":resource_names} with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps(graphic_and_asset)) else: + write_data = copy.deepcopy(data) + write_data["resources"] = resource_names with open(os.path.join(base_path, self.name + ".asset"), "w") as f: - f.write(pretty_dumps(data)) + f.write(pretty_dumps(write_data)) for name,details in data.iteritems(): with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps({"data":self.name + ".asset"})) diff --git a/old/Checkbox.as b/old/Checkbox.as deleted file mode 100644 index c5aaba2..0000000 --- a/old/Checkbox.as +++ /dev/null @@ -1,42 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - - public class Checkbox extends MovieClip - { - public var Enabled:Boolean = true; - public function Checkbox() - { - checkbox.gotoAndStop(1); - checkbox.addEventListener(MouseEvent.CLICK, Clicked); - } - - protected function Clicked(event) - { - if (!Enabled) return; - Toggle(); - if (OnClick != null) OnClick(OnClickParam); - } - - protected var checked = false; - public function set Checked(value) { checked = value; checkbox.gotoAndStop(checked ? 2 : 1); } - public function get Checked() { return checked; } - - public function set Text(value) { text.text = value; } - - public var OnClickParam; - public var OnClick; - - - public function Toggle() - { - checked = !checked; - checkbox.gotoAndStop(checked ? 2 : 1); - - - } - - } - -} diff --git a/old/GraphicExport-app.xml b/old/GraphicExport-app.xml deleted file mode 100644 index 5144634..0000000 --- a/old/GraphicExport-app.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - GraphicExport - 1.0 - GraphicExport - - GraphicExport - - - GraphicExport.swf - standard - false - true - false - portrait - auto - true - true - true - - - false - false - desktop extendedDesktop diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/flash/util/RectangleNode.as b/flash/util/RectangleNode.as new file mode 100644 index 0000000..6f31e44 --- /dev/null +++ b/flash/util/RectangleNode.as @@ -0,0 +1,178 @@ +package util { + import flash.geom.Rectangle; + + public class RectangleNode + { + public var Left:RectangleNode = null; + public var Right:RectangleNode = null; + public var Rect:Rectangle = null; + public var InUse:Boolean = false; + public var Removed:Boolean = false; + public var Parent:RectangleNode = null; + public var AllocationID = 0; + public var Host:RectanglePacker= null; + public var MinAllocationID = 0; + public var NodeID; + public static var NextNodeID = 0; + + public var DontRemove = false; + + public var LastAccessTime = 0; + + public var Flags = []; + + public var UpdateTo:RectangleNode = null; + + /* + public function get Removed() + { + return _Removed; + } + + public function set Removed(r) + { + this._Removed = r; + } + + public function get Host():RectanglePacker + { + return _Host; + } + public function set Host(p:RectanglePacker) + { + this._Host = p; + + if (_Left && _Left.Host != p) + { + throw new Error("bad left host"); + } + if (_Right && _Right.Host != p) + { + throw new Error("bad right host"); + } + if (_Parent && _Parent.Host != p) + { + throw new Error("bad parent host"); + } + + } + + public function get Left():RectangleNode + { + return _Left; + } + public function set Left(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad left host"); + } + _Left = n; + } + public function get Right():RectangleNode + { + return _Right; + } + public function set Right(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad right host"); + } + _Right = n; + } + + public function get Parent():RectangleNode + { + return _Parent; + } + public function set Parent(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad parent host"); + } + _Parent = n; + } + */ + public function get IsFreeSpace() + { + return Left == null && Right == null && !InUse; + } + public function UpdateLinksFromNode(node:RectangleNode) + { + if (node.Parent) + { + if (node.Parent.Left == node) + { + node.Parent.Left = this; + } + if (node.Parent.Right == node) + { + node.Parent.Right = this; + } + } + if (node.Left) + { + node.Left.Parent = this; + } + if (node.Right) + { + node.Right.Parent = this; + } + } + public function MakeFromNode(node:RectangleNode) + { + //_Host = node.Host; + Host = node.Host; + Left = node.Left; + Right = node.Right; + Parent = node.Parent; + AllocationID = node.AllocationID; + InUse = node.InUse; + MinAllocationID = node.MinAllocationID; + NodeID = node.NodeID; + Rect = node.Rect.clone(); + Removed = node.Removed; + DontRemove = node.DontRemove; + } + public function RectangleNode(x, y, w, h, host:RectanglePacker) + { + this.NodeID = NextNodeID++; + this.Host = host; + this.Rect = new Rectangle(x, y, w, h); + } + public function OutputJSON() + { + var node = {}; + node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; + node.in_use = InUse; + node.id = NodeID; + if (this.Left) node.left = this.Left.OutputJSON(); + if (this.Right) node.right = this.Right.OutputJSON(); + return node; + } + + public function ReadJSON(details) + { + details.new_node = this; + this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); + this.Removed = false; + + this.InUse = details.in_use; + + if (details.hasOwnProperty("right")) + { + this.Right = new RectangleNode(0, 0, 0, 0, this.Host); + Right.ReadJSON(details.right); + Right.Parent = this; + } + if (details.hasOwnProperty("left")) + { + this.Left = new RectangleNode(0, 0, 0, 0, this.Host); + Left.ReadJSON(details.left); + Left.Parent = this; + } + } + } +} diff --git a/flash/util/RectanglePacker.as b/flash/util/RectanglePacker.as new file mode 100644 index 0000000..597d7fd --- /dev/null +++ b/flash/util/RectanglePacker.as @@ -0,0 +1,562 @@ +package util { + import flash.geom.*; + import flash.display.BitmapData; + import flash.display.MovieClip; + import flash.text.TextField; + import flash.events.*; + import flash.sampler.StackFrame; + + public class RectanglePacker + { + protected var w:int; + protected var h:int; + protected var root:RectangleNode; + public var NextAllocationID = 0; + + public function get width():int { return w; } + public function get height():int { return h; } + + public function RectanglePacker(w, h) + { + this.w = w; + this.h = h; + root = new RectangleNode(0, 0, w, h, this); + root.AllocationID = -1; + } + protected var area = 0; + + protected var testRender:MovieClip = new MovieClip(); + + public function GetRoot():RectangleNode + { + return root; + } + + public function GetLeafNodes():Array + { + return GetLeafNodesInternal(root); + } + + protected function GetLeafNodesInternal(n:RectangleNode):Array + { + if (n.InUse) return [n]; + var ret:Array = new Array(); + if (n.Left) ret = GetLeafNodesInternal(n.Left); + if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); + return ret; + } + + public function GetUsedArea() + { + return area; + } + + public function get efficiency() + { + return area / (w * h); + } + + protected function RectCost(w, h) + { + if (w == 0 || h == 0) return 99999999; + return (Math.max(w, h) / Math.min(w, h)) * w * h; + } + + protected function EnumerateTree(r:RectangleNode = null, indent = "") + { + if (r == null) r = this.root; + var str = ""; + str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; + if (r.Left) str += EnumerateTree(r.Left, indent + " "); + if (r.Right) str += EnumerateTree(r.Left, indent + " "); + return str; + } + + /* + * Remove a list of nodes from the tree. + * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree + * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, + leaving the original objects intact (in case something still references them) + */ + public function RemoveNodes(nodes:Array, fullyDestroy = true) + { + + /* DEBUG CHECKS */ + /* + this.PerformDebugCheck(); + + var str = ""; + for (var i = 0; i < nodes.length; i++) + { + str += nodes[i].NodeID + "\n"; + } + + var orig = nodes.concat(); + + var strs = [str, EnumerateTree()]; + + RenderDetailsBox.StartTrack("PackRemoveTime"); + + for (var i = 0; i < nodes.length; i++) + { + var n:RectangleNode = nodes[i]; + if (n.Host != this) + { + throw new Error("bad host!"); + } + } + */ + /* END DEBUG CHECKS */ + + var i, n:RectangleNode, p:RectangleNode; + + // setup the Removed flag on every node that should be removed + // we also check at this time to see if any more nodes need to be removed, such as a parent of + // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + if (n.Host == this) + { + n.Removed = true; + + if (n.InUse) + { + // sum up the total removed area + area -= n.Rect.width * n.Rect.height; + } + + if (n.Parent != null) + { + p = n.Parent; + // check and see if the current node's parent still has any valid children + if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) + { + // all of the current nodes siblings are either being removed or are blank, so + // we can remove the parent too + if (p.Left.IsFreeSpace) + { + // the left child was empty space before, so we can remove it (if it wasn't + // empty space it is already being removed so it doesn't need to be added + // to the list) + if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); + } + if (p.Right.IsFreeSpace) + { + // the right child was empty space before, so we can remove it + if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); + } + if (p != root && nodes.indexOf(p) == -1) + { + // remove the parent node too (provided it isn't the root!) + nodes.push(p); + } + } + } + } + } + + // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, + // so go ahead and remove them + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + + if (n.Parent != null) + { + // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not + // also getting removed!) + p = n.Parent; + + if (!p.Removed) + { + if (p.Left && p.Right) + { + var newNode:RectangleNode; + if (p.Left.Removed && p.Right.Removed) + { + // both children were removed, but the parent wasn't, so the parent must be root + // (since we never remove the root) + if (p != root) + { + throw new Error("should be root"); + } + p.Left.Parent = null; + p.Right.Parent = null; + p.Left = null; + p.Right = null; + p.InUse = false; + } else if (!p.Left.Removed) { + // Right node removed, Left node not removed + if (!p.Left.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Right); + newNode.UpdateLinksFromNode(p.Right); + } + // Left node is used + p.Right.InUse = false; + p.Right.Left = null; + p.Right.Right = null; + p.Right.Removed = false; + } else { + throw new Error("should have been caught above!"); + } + } else { + // Left node removed, Right node not removed + if (!p.Right.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Left); + newNode.UpdateLinksFromNode(p.Left); + } + // Left node is used + //p.Left.Removed = true; + p.Left.InUse = false; + p.Left.Left = null; + p.Left.Right = null; + p.Left.Removed = false; + //p.Left.Parent = null; + } else { + throw new Error("should have been caught above!"); + } + } + } else { + // huh? how does n.Parent == p but p has no children? something went wrong + throw new Error("shouldn't have gotten here"); + } + } + } + //strs.push(EnumerateTree()); + } + } + + public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode + { + + var node:RectangleNode = FindSizedNode(w, h, root); + + if (node == null) + { + //UHOH, texture full + return null; + } + area += w * h; + node.InUse = true; + + var splitVertFirstCost = 0; + if (w < node.Rect.width) + { + splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); + } + + var splitHorizFirstCost = 0; + if (h < node.Rect.height) + { + splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); + } + + + + if (splitVertFirstCost <= splitHorizFirstCost) + { + node.Flags.push("SplitVertFirst"); + if (w < node.Rect.width) + { + node.Flags.push("SplitVert"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + if (h < node.Rect.height) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + } else { + node.Flags.push("SplitHorzFirst"); + if (h < node.Rect.height) + { + node.Flags.push("SplitVert"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + if (w < node.Rect.width) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + } + NextAllocationID++; + if (useInstead) + { + useInstead.MakeFromNode(node); + useInstead.UpdateLinksFromNode(node); + useInstead.Flags = node.Flags; + node = useInstead; + node.Flags.push("UseInstead"); + } + + //if (!CheckOKNode(node)) node.Flags.push("BadNode"); + + return node; + } + public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) + { + if (r == null) r = this.root; + if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) + { + var ancestor:RectangleNode = FindCommonNode(n, r); + throw new Error("bad node allocated!"); + return false; + } + var ok = true; + if (r.Left) ok = ok && CheckOKNode(n, r.Left); + if (r.Right) ok = ok && CheckOKNode(n, r.Right); + return ok; + } + + public function PerformDebugCheck() + { + DebugInternal(this.root); + } + + protected function DebugInternal(n:RectangleNode) + { + if (n.Host != this) + { + throw new Error("problem with host!"); + } + if (n.IsFreeSpace) + { + if (n.Left || n.Right) + { + throw new Error("shouldn't have children"); + } + } + if ((n.Left && !n.Right) || (n.Right && !n.Left)) + { + throw new Error("mismatched children"); + } + if (n.Left && n.Left.Parent != n) + { + throw new Error("left child has bad parent"); + } + if (n.Right && n.Right.Parent != n) + { + throw new Error("right child has bad parent"); + } + if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) + { + throw new Error("problem with parent"); + } + if (n.Left) DebugInternal(n.Left); + if (n.Right) DebugInternal(n.Right); + } + + public function FindCommonNode(a:RectangleNode, b:RectangleNode) + { + var aHistory = []; + var bHistory = []; + while (a != null) + { + aHistory.push(a); + a = a.Parent; + } + while (b != null) + { + bHistory.push(b); + b = b.Parent; + } + var i = aHistory.length - 1; + var j = bHistory.length - 1; + var same = null; + while (i >= 0 && j >= 0) + { + if (aHistory[i] == bHistory[j]) + { + same = aHistory[i]; + } else { + break; + } + i--; + j--; + } + return same; + } + + public function TestRender() + { + while (testRender.numChildren > 0) + { + testRender.removeChildAt(0); + } + testRender.graphics.clear(); + TestRenderNode(root, testRender); + return testRender; + } + protected function TestRenderNode(n:RectangleNode, m:MovieClip) + { + var g:MovieClip = new MovieClip(); + m.addChild(g); + g.graphics.lineStyle(1, 0, 1); + if (n.Left != null) TestRenderNode(n.Left, m); + if (n.Left != null) TestRenderNode(n.Right, m); + if (n.InUse) + { + g.graphics.beginFill(0xFFFF00, 0.2); + } + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + if (n.InUse) + { + g.graphics.endFill(); + var t:TextField = new TextField(); + t.text = n.NodeID; + t.x = n.Rect.x + n.Rect.width / 2.0; + t.y = n.Rect.y + n.Rect.height / 2.0; + g.addChild(t); + g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); + g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); + } + + } + public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) + { + if (n.InUse) + { + //_trace(Math.round(n.LastAccessTime / 1000)); + } + var p:RectangleNode = n.Parent; + if (p) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); + g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); + g.graphics.endFill(); + t.text = p.NodeID; + if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); + g.oldListener = function(e){MouseOver(p, g, t);}; + g.addEventListener(MouseEvent.CLICK, g.oldListener); + } + } + public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(0xFFFF00, 0.2); + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + g.graphics.endFill(); + t.text = n.NodeID; + } + protected function SplitVert(node:RectangleNode, leftWidth) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function SplitHoriz(node:RectangleNode, topHeight) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode + { + if (node.InUse) return null; + if (node.Rect.width >= w && node.Rect.height >= h) + { + if (node.Left != null && node.Right != null) + { + var t:RectangleNode = FindSizedNode(w, h, node.Left); + if (t != null) return t; + t = FindSizedNode(w, h, node.Right); + return t; + } else { + return node; + } + } + return null; + } + + public function LoadTree(details) + { + this.root = new RectangleNode(0, 0, 0, 0, this); + root.ReadJSON(details); + + this.NextAllocationID = 0; + this.area = 0; + + var queue:Array = new Array(); + queue.push(root); + while (queue.length > 0) + { + var node:RectangleNode = queue.shift(); + node.AllocationID = NextAllocationID; + node.MinAllocationID = NextAllocationID; + if (node.Left) queue.push(node.Left); + if (node.Right) queue.push(node.Right); + if (node.InUse) this.area += node.Rect.width * node.Rect.height; + } + NextAllocationID++; + } + + public function GetNodePath(node:RectangleNode) + { + var output:String = ""; + while (node != this.root) + { + output = (node == node.Parent.Left ? "l" : "r") + output; + node = node.Parent; + } + return output; + } + + public function GetNodeFromPath(path:String):RectangleNode + { + var node:RectangleNode = this.root; + for (var i = 0; i < path.length; i++) + { + if (!node) return null; + if (path.charAt(i) == "r") + { + node = node.Right; + } else { + node = node.Left; + } + } + return node; + } + } +} diff --git a/flash/util/Utils.as b/flash/util/Utils.as new file mode 100644 index 0000000..f792003 --- /dev/null +++ b/flash/util/Utils.as @@ -0,0 +1,389 @@ +package util +{ + import flash.display.*; + import flash.geom.*; + public class Utils + { + public static function GetChildren(clip:MovieClip):Array + { + var ret:Array = []; + for (var i = 0; i < clip.numChildren; i++) + { + ret.push(clip.getChildAt(i)); + } + return ret; + } + + /* + * angle difference + * (range -Math.PI to Math.PI) + */ + public static function GetAngleDiff(a, b) + { + var angleDiff = b - a; + + while (angleDiff > Math.PI) + { + angleDiff -= Math.PI * 2; + } + while (angleDiff < -Math.PI) + { + angleDiff += Math.PI * 2; + } + return angleDiff; + } + + /* + * angle difference + * (range 0 to Math.PI) + */ + public static function GetAngleDiffAbs(a, b) + { + var angleDiff = GetAngleDiff(a, b); + while (angleDiff < 0) + { + angleDiff += Math.PI * 2; + } + + if (angleDiff > Math.PI) + { + angleDiff = Math.PI * 2 - angleDiff; + } + + return angleDiff; + } + + public static function GetTransform(from:Matrix, to:Matrix) + { + var i:Matrix = from.clone(); + i.invert(); + var m:Matrix = to.clone(); + m.concat(i); + return m; + } + + public static function Decompose(m:Matrix) + { + var s:Point = ScaleFromMat(m); + m = m.clone(); + + var sxUnit = s.x >= 0 ? 1 : -1; + var syUnit = s.y >= 0 ? 1 : -1; + + m.scale(sxUnit, syUnit); + + //m.a /= sxUnit; + //m.d /= syUnit; + var rot = RotFromMat(m); + return {sx:s.x, sy:s.y, rot:rot}; + } + + public static function RotFromMat(m:Matrix) + { + return Math.atan2(-m.c, m.a); + } + + public static function ScaleFromMat(m:Matrix):Point + { + var xAxisX = m.a; + var xAxisY = m.c; + + var yAxisX = m.b; + var yAxisY = m.d; + + var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); + if (m.a < 0) sx *= -1; + + var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); + if (m.d < 0) sy *= -1; + + return new Point(sx, sy); + } + + public static function TransformRect(r:Rectangle, m:Matrix) + { + var p1:Point = new Point(r.left, r.top); + var p2:Point = new Point(r.right, r.top); + var p3:Point = new Point(r.left, r.bottom); + var p4:Point = new Point(r.right, r.bottom); + + p1 = m.transformPoint(p1); + p2 = m.transformPoint(p2); + p3 = m.transformPoint(p3); + p4 = m.transformPoint(p4); + + r.left = Math.min(p1.x, p2.x, p3.x, p4.x); + r.top = Math.min(p1.y, p2.y, p3.y, p4.y); + r.right = Math.max(p1.x, p2.x, p3.x, p4.x); + r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); + } + + public static function RoundRect(r:Rectangle) + { + r.left = Math.floor(r.left); + r.top = Math.floor(r.top); + r.right = Math.ceil(r.right); + r.bottom = Math.ceil(r.bottom); + } + + public static function ScaleRect(r:Rectangle, s) + { + r.left *= s; + r.top *= s; + r.right *= s; + r.bottom *= s; + } + + public static function RecursivelyStop(clip) + { + if (clip is MovieClip) + { + clip.stop(); + } + if (clip is DisplayObjectContainer) + { + for (var i = 0; i < clip.numChildren; i++) + { + RecursivelyStop(clip.getChildAt(i)); + } + } + } + + public static function WeirdGotoFrame(clip:MovieClip, frame) + { + var dir = clip.currentFrame > frame ? -1 : 1; + while (clip.currentFrame != frame) + { + RecurseDir(clip, dir); + } + } + + protected static function RecurseDir(clip:MovieClip, dir) + { + for (var i = 0; i < clip.numChildren; i++) + { + var child = clip.getChildAt(i); + if (child is MovieClip) + { + RecurseDir(child, dir); + } + } + if (dir == 1) + { + clip.nextFrame(); + } else { + clip.prevFrame(); + } + } + + protected static var tempSpace:BitmapData = null; + protected static var tempSpaceRect:Rectangle = new Rectangle(); + protected static var tempSpaceMatrix:Matrix = new Matrix(); + protected static var tempSpaceZero:Point = new Point(); + protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); + protected static var lastDrawOffset:Point = new Point(); + public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle + { + if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); + + var oldPad = 0; + var padAmount = 5; + + var ret:Rectangle = new Rectangle(); + + var baseBounds:Rectangle = clip.getBounds(clip); + + var boundsClip:DisplayObject = null; + if (clip is DisplayObjectContainer) + { + boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); + } + + if (boundsClip != null) + { + baseBounds = boundsClip.getBounds(clip); + } + + if (useMatrix) + { + TransformAABBRect(baseBounds, useMatrix); + } + + if (boundsClip != null) + { + return baseBounds; + } + + var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); + var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); + if (tempSpace == null) + { + tempSpace = new BitmapData(minW, minH, true, 0x0); + } + if (tempSpace.width < minW || tempSpace.height < minH) + { + tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); + } + + var r:Rectangle = new Rectangle(); + + baseBounds.left = Math.floor(baseBounds.left); + baseBounds.right = Math.ceil(baseBounds.right); + + baseBounds.top = Math.floor(baseBounds.top); + baseBounds.bottom = Math.ceil(baseBounds.bottom); + + var i; + + var needsChecking = true; + while (needsChecking) + { + needsChecking = false; + r.left = baseBounds.left - padAmount; + r.right = baseBounds.right + padAmount; + + r.top = baseBounds.top - padAmount; + r.bottom = baseBounds.bottom + padAmount; + + ret = r.clone(); + + tempSpaceRect.x = tempSpaceRect.y = 0; + tempSpaceRect.width = tempSpace.width; + tempSpaceRect.height = tempSpace.height; + tempSpace.fillRect(tempSpaceRect, 0x0); + + tempSpaceMatrix.identity(); + if (useMatrix) + { + tempSpaceMatrix.a = useMatrix.a; + tempSpaceMatrix.b = useMatrix.b; + tempSpaceMatrix.c = useMatrix.c; + tempSpaceMatrix.d = useMatrix.d; + tempSpaceMatrix.tx = useMatrix.tx; + tempSpaceMatrix.ty = useMatrix.ty; + } + tempSpaceMatrix.translate(-r.left, -r.top); + + lastDrawOffset.x = -r.left; + lastDrawOffset.y = -r.top; + tempSpace.draw(clip, tempSpaceMatrix); + + tempSpaceRect.width = 1; + tempSpaceRect.height = r.height; + + var sideMovedIn = 0; + for (i = 0; i < r.width; i++) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.left++; + sideMovedIn++; + } + } + if (ret.left < baseBounds.left - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.width - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.right--; + } + } + if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + sideMovedIn = 0; + tempSpaceRect.width = r.width; + tempSpaceRect.height = 1; + tempSpaceRect.x = 0; + for (i = 0; i < r.height; i++) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.top++; + sideMovedIn++; + } + } + if (ret.top < baseBounds.top - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.height - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.bottom--; + } + } + if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + } + return ret; + } + + public static function TransformAABBRect(r:Rectangle, m:Matrix) + { + var o1X = r.left; + var o1Y = r.top; + + var o2X = r.right; + var o2Y = r.top; + + var o3X = r.left; + var o3Y = r.bottom; + + var o4X = r.right; + var o4Y = r.bottom; + + var n1X = o1X * m.a + o1Y * m.c + m.tx; + var n1Y = o1X * m.b + o1Y * m.d + m.ty; + + var n2X = o2X * m.a + o2Y * m.c + m.tx; + var n2Y = o2X * m.b + o2Y * m.d + m.ty; + + var n3X = o3X * m.a + o3Y * m.c + m.tx; + var n3Y = o3X * m.b + o3Y * m.d + m.ty; + + var n4X = o4X * m.a + o4Y * m.c + m.tx; + var n4Y = o4X * m.b + o4Y * m.d + m.ty; + + r.left = Math.min(n1X, n2X, n3X, n4X); + r.right = Math.max(n1X, n2X, n3X, n4X); + + r.top = Math.min(n1Y, n2Y, n3Y, n4Y); + r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); + } + } +} diff --git a/job.py b/job.py index 989c991..77c09e8 100644 --- a/job.py +++ b/job.py @@ -3,6 +3,7 @@ import json from validate import * from args import * +import copy asset_src_schema = { "type":"object", @@ -69,19 +70,24 @@ base_path = os.path.join(self.out_dir, self.rel_path) if not os.path.exists(base_path): os.makedirs(base_path) + resource_names = [] for i,r in enumerate(resources): - path = os.path.join(base_path, "%s_%04d.png" % (self.name, i)) + resource_name = "%s_%04d.png" % (self.name, i) if len(resources) > 1 else self.name + ".png" + resource_names.append(resource_name) + path = os.path.join(base_path, resource_name) with open(path, "wb") as f: f.write(base64.b64decode(r)) if len(data) == 1: graphic_and_asset = {} (name, graphic_data) = data.items()[0] - graphic_and_asset = {"data":graphic_data} + graphic_and_asset = {"data":graphic_data, "resources":resource_names} with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps(graphic_and_asset)) else: + write_data = copy.deepcopy(data) + write_data["resources"] = resource_names with open(os.path.join(base_path, self.name + ".asset"), "w") as f: - f.write(pretty_dumps(data)) + f.write(pretty_dumps(write_data)) for name,details in data.iteritems(): with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps({"data":self.name + ".asset"})) diff --git a/old/Checkbox.as b/old/Checkbox.as deleted file mode 100644 index c5aaba2..0000000 --- a/old/Checkbox.as +++ /dev/null @@ -1,42 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - - public class Checkbox extends MovieClip - { - public var Enabled:Boolean = true; - public function Checkbox() - { - checkbox.gotoAndStop(1); - checkbox.addEventListener(MouseEvent.CLICK, Clicked); - } - - protected function Clicked(event) - { - if (!Enabled) return; - Toggle(); - if (OnClick != null) OnClick(OnClickParam); - } - - protected var checked = false; - public function set Checked(value) { checked = value; checkbox.gotoAndStop(checked ? 2 : 1); } - public function get Checked() { return checked; } - - public function set Text(value) { text.text = value; } - - public var OnClickParam; - public var OnClick; - - - public function Toggle() - { - checked = !checked; - checkbox.gotoAndStop(checked ? 2 : 1); - - - } - - } - -} diff --git a/old/GraphicExport-app.xml b/old/GraphicExport-app.xml deleted file mode 100644 index 5144634..0000000 --- a/old/GraphicExport-app.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - GraphicExport - 1.0 - GraphicExport - - GraphicExport - - - GraphicExport.swf - standard - false - true - false - portrait - auto - true - true - true - - - false - false - desktop extendedDesktop diff --git a/old/GraphicExport.exe b/old/GraphicExport.exe deleted file mode 100644 index 56315aa..0000000 --- a/old/GraphicExport.exe +++ /dev/null Binary files differ diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/flash/util/RectangleNode.as b/flash/util/RectangleNode.as new file mode 100644 index 0000000..6f31e44 --- /dev/null +++ b/flash/util/RectangleNode.as @@ -0,0 +1,178 @@ +package util { + import flash.geom.Rectangle; + + public class RectangleNode + { + public var Left:RectangleNode = null; + public var Right:RectangleNode = null; + public var Rect:Rectangle = null; + public var InUse:Boolean = false; + public var Removed:Boolean = false; + public var Parent:RectangleNode = null; + public var AllocationID = 0; + public var Host:RectanglePacker= null; + public var MinAllocationID = 0; + public var NodeID; + public static var NextNodeID = 0; + + public var DontRemove = false; + + public var LastAccessTime = 0; + + public var Flags = []; + + public var UpdateTo:RectangleNode = null; + + /* + public function get Removed() + { + return _Removed; + } + + public function set Removed(r) + { + this._Removed = r; + } + + public function get Host():RectanglePacker + { + return _Host; + } + public function set Host(p:RectanglePacker) + { + this._Host = p; + + if (_Left && _Left.Host != p) + { + throw new Error("bad left host"); + } + if (_Right && _Right.Host != p) + { + throw new Error("bad right host"); + } + if (_Parent && _Parent.Host != p) + { + throw new Error("bad parent host"); + } + + } + + public function get Left():RectangleNode + { + return _Left; + } + public function set Left(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad left host"); + } + _Left = n; + } + public function get Right():RectangleNode + { + return _Right; + } + public function set Right(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad right host"); + } + _Right = n; + } + + public function get Parent():RectangleNode + { + return _Parent; + } + public function set Parent(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad parent host"); + } + _Parent = n; + } + */ + public function get IsFreeSpace() + { + return Left == null && Right == null && !InUse; + } + public function UpdateLinksFromNode(node:RectangleNode) + { + if (node.Parent) + { + if (node.Parent.Left == node) + { + node.Parent.Left = this; + } + if (node.Parent.Right == node) + { + node.Parent.Right = this; + } + } + if (node.Left) + { + node.Left.Parent = this; + } + if (node.Right) + { + node.Right.Parent = this; + } + } + public function MakeFromNode(node:RectangleNode) + { + //_Host = node.Host; + Host = node.Host; + Left = node.Left; + Right = node.Right; + Parent = node.Parent; + AllocationID = node.AllocationID; + InUse = node.InUse; + MinAllocationID = node.MinAllocationID; + NodeID = node.NodeID; + Rect = node.Rect.clone(); + Removed = node.Removed; + DontRemove = node.DontRemove; + } + public function RectangleNode(x, y, w, h, host:RectanglePacker) + { + this.NodeID = NextNodeID++; + this.Host = host; + this.Rect = new Rectangle(x, y, w, h); + } + public function OutputJSON() + { + var node = {}; + node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; + node.in_use = InUse; + node.id = NodeID; + if (this.Left) node.left = this.Left.OutputJSON(); + if (this.Right) node.right = this.Right.OutputJSON(); + return node; + } + + public function ReadJSON(details) + { + details.new_node = this; + this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); + this.Removed = false; + + this.InUse = details.in_use; + + if (details.hasOwnProperty("right")) + { + this.Right = new RectangleNode(0, 0, 0, 0, this.Host); + Right.ReadJSON(details.right); + Right.Parent = this; + } + if (details.hasOwnProperty("left")) + { + this.Left = new RectangleNode(0, 0, 0, 0, this.Host); + Left.ReadJSON(details.left); + Left.Parent = this; + } + } + } +} diff --git a/flash/util/RectanglePacker.as b/flash/util/RectanglePacker.as new file mode 100644 index 0000000..597d7fd --- /dev/null +++ b/flash/util/RectanglePacker.as @@ -0,0 +1,562 @@ +package util { + import flash.geom.*; + import flash.display.BitmapData; + import flash.display.MovieClip; + import flash.text.TextField; + import flash.events.*; + import flash.sampler.StackFrame; + + public class RectanglePacker + { + protected var w:int; + protected var h:int; + protected var root:RectangleNode; + public var NextAllocationID = 0; + + public function get width():int { return w; } + public function get height():int { return h; } + + public function RectanglePacker(w, h) + { + this.w = w; + this.h = h; + root = new RectangleNode(0, 0, w, h, this); + root.AllocationID = -1; + } + protected var area = 0; + + protected var testRender:MovieClip = new MovieClip(); + + public function GetRoot():RectangleNode + { + return root; + } + + public function GetLeafNodes():Array + { + return GetLeafNodesInternal(root); + } + + protected function GetLeafNodesInternal(n:RectangleNode):Array + { + if (n.InUse) return [n]; + var ret:Array = new Array(); + if (n.Left) ret = GetLeafNodesInternal(n.Left); + if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); + return ret; + } + + public function GetUsedArea() + { + return area; + } + + public function get efficiency() + { + return area / (w * h); + } + + protected function RectCost(w, h) + { + if (w == 0 || h == 0) return 99999999; + return (Math.max(w, h) / Math.min(w, h)) * w * h; + } + + protected function EnumerateTree(r:RectangleNode = null, indent = "") + { + if (r == null) r = this.root; + var str = ""; + str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; + if (r.Left) str += EnumerateTree(r.Left, indent + " "); + if (r.Right) str += EnumerateTree(r.Left, indent + " "); + return str; + } + + /* + * Remove a list of nodes from the tree. + * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree + * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, + leaving the original objects intact (in case something still references them) + */ + public function RemoveNodes(nodes:Array, fullyDestroy = true) + { + + /* DEBUG CHECKS */ + /* + this.PerformDebugCheck(); + + var str = ""; + for (var i = 0; i < nodes.length; i++) + { + str += nodes[i].NodeID + "\n"; + } + + var orig = nodes.concat(); + + var strs = [str, EnumerateTree()]; + + RenderDetailsBox.StartTrack("PackRemoveTime"); + + for (var i = 0; i < nodes.length; i++) + { + var n:RectangleNode = nodes[i]; + if (n.Host != this) + { + throw new Error("bad host!"); + } + } + */ + /* END DEBUG CHECKS */ + + var i, n:RectangleNode, p:RectangleNode; + + // setup the Removed flag on every node that should be removed + // we also check at this time to see if any more nodes need to be removed, such as a parent of + // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + if (n.Host == this) + { + n.Removed = true; + + if (n.InUse) + { + // sum up the total removed area + area -= n.Rect.width * n.Rect.height; + } + + if (n.Parent != null) + { + p = n.Parent; + // check and see if the current node's parent still has any valid children + if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) + { + // all of the current nodes siblings are either being removed or are blank, so + // we can remove the parent too + if (p.Left.IsFreeSpace) + { + // the left child was empty space before, so we can remove it (if it wasn't + // empty space it is already being removed so it doesn't need to be added + // to the list) + if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); + } + if (p.Right.IsFreeSpace) + { + // the right child was empty space before, so we can remove it + if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); + } + if (p != root && nodes.indexOf(p) == -1) + { + // remove the parent node too (provided it isn't the root!) + nodes.push(p); + } + } + } + } + } + + // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, + // so go ahead and remove them + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + + if (n.Parent != null) + { + // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not + // also getting removed!) + p = n.Parent; + + if (!p.Removed) + { + if (p.Left && p.Right) + { + var newNode:RectangleNode; + if (p.Left.Removed && p.Right.Removed) + { + // both children were removed, but the parent wasn't, so the parent must be root + // (since we never remove the root) + if (p != root) + { + throw new Error("should be root"); + } + p.Left.Parent = null; + p.Right.Parent = null; + p.Left = null; + p.Right = null; + p.InUse = false; + } else if (!p.Left.Removed) { + // Right node removed, Left node not removed + if (!p.Left.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Right); + newNode.UpdateLinksFromNode(p.Right); + } + // Left node is used + p.Right.InUse = false; + p.Right.Left = null; + p.Right.Right = null; + p.Right.Removed = false; + } else { + throw new Error("should have been caught above!"); + } + } else { + // Left node removed, Right node not removed + if (!p.Right.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Left); + newNode.UpdateLinksFromNode(p.Left); + } + // Left node is used + //p.Left.Removed = true; + p.Left.InUse = false; + p.Left.Left = null; + p.Left.Right = null; + p.Left.Removed = false; + //p.Left.Parent = null; + } else { + throw new Error("should have been caught above!"); + } + } + } else { + // huh? how does n.Parent == p but p has no children? something went wrong + throw new Error("shouldn't have gotten here"); + } + } + } + //strs.push(EnumerateTree()); + } + } + + public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode + { + + var node:RectangleNode = FindSizedNode(w, h, root); + + if (node == null) + { + //UHOH, texture full + return null; + } + area += w * h; + node.InUse = true; + + var splitVertFirstCost = 0; + if (w < node.Rect.width) + { + splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); + } + + var splitHorizFirstCost = 0; + if (h < node.Rect.height) + { + splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); + } + + + + if (splitVertFirstCost <= splitHorizFirstCost) + { + node.Flags.push("SplitVertFirst"); + if (w < node.Rect.width) + { + node.Flags.push("SplitVert"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + if (h < node.Rect.height) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + } else { + node.Flags.push("SplitHorzFirst"); + if (h < node.Rect.height) + { + node.Flags.push("SplitVert"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + if (w < node.Rect.width) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + } + NextAllocationID++; + if (useInstead) + { + useInstead.MakeFromNode(node); + useInstead.UpdateLinksFromNode(node); + useInstead.Flags = node.Flags; + node = useInstead; + node.Flags.push("UseInstead"); + } + + //if (!CheckOKNode(node)) node.Flags.push("BadNode"); + + return node; + } + public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) + { + if (r == null) r = this.root; + if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) + { + var ancestor:RectangleNode = FindCommonNode(n, r); + throw new Error("bad node allocated!"); + return false; + } + var ok = true; + if (r.Left) ok = ok && CheckOKNode(n, r.Left); + if (r.Right) ok = ok && CheckOKNode(n, r.Right); + return ok; + } + + public function PerformDebugCheck() + { + DebugInternal(this.root); + } + + protected function DebugInternal(n:RectangleNode) + { + if (n.Host != this) + { + throw new Error("problem with host!"); + } + if (n.IsFreeSpace) + { + if (n.Left || n.Right) + { + throw new Error("shouldn't have children"); + } + } + if ((n.Left && !n.Right) || (n.Right && !n.Left)) + { + throw new Error("mismatched children"); + } + if (n.Left && n.Left.Parent != n) + { + throw new Error("left child has bad parent"); + } + if (n.Right && n.Right.Parent != n) + { + throw new Error("right child has bad parent"); + } + if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) + { + throw new Error("problem with parent"); + } + if (n.Left) DebugInternal(n.Left); + if (n.Right) DebugInternal(n.Right); + } + + public function FindCommonNode(a:RectangleNode, b:RectangleNode) + { + var aHistory = []; + var bHistory = []; + while (a != null) + { + aHistory.push(a); + a = a.Parent; + } + while (b != null) + { + bHistory.push(b); + b = b.Parent; + } + var i = aHistory.length - 1; + var j = bHistory.length - 1; + var same = null; + while (i >= 0 && j >= 0) + { + if (aHistory[i] == bHistory[j]) + { + same = aHistory[i]; + } else { + break; + } + i--; + j--; + } + return same; + } + + public function TestRender() + { + while (testRender.numChildren > 0) + { + testRender.removeChildAt(0); + } + testRender.graphics.clear(); + TestRenderNode(root, testRender); + return testRender; + } + protected function TestRenderNode(n:RectangleNode, m:MovieClip) + { + var g:MovieClip = new MovieClip(); + m.addChild(g); + g.graphics.lineStyle(1, 0, 1); + if (n.Left != null) TestRenderNode(n.Left, m); + if (n.Left != null) TestRenderNode(n.Right, m); + if (n.InUse) + { + g.graphics.beginFill(0xFFFF00, 0.2); + } + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + if (n.InUse) + { + g.graphics.endFill(); + var t:TextField = new TextField(); + t.text = n.NodeID; + t.x = n.Rect.x + n.Rect.width / 2.0; + t.y = n.Rect.y + n.Rect.height / 2.0; + g.addChild(t); + g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); + g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); + } + + } + public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) + { + if (n.InUse) + { + //_trace(Math.round(n.LastAccessTime / 1000)); + } + var p:RectangleNode = n.Parent; + if (p) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); + g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); + g.graphics.endFill(); + t.text = p.NodeID; + if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); + g.oldListener = function(e){MouseOver(p, g, t);}; + g.addEventListener(MouseEvent.CLICK, g.oldListener); + } + } + public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(0xFFFF00, 0.2); + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + g.graphics.endFill(); + t.text = n.NodeID; + } + protected function SplitVert(node:RectangleNode, leftWidth) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function SplitHoriz(node:RectangleNode, topHeight) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode + { + if (node.InUse) return null; + if (node.Rect.width >= w && node.Rect.height >= h) + { + if (node.Left != null && node.Right != null) + { + var t:RectangleNode = FindSizedNode(w, h, node.Left); + if (t != null) return t; + t = FindSizedNode(w, h, node.Right); + return t; + } else { + return node; + } + } + return null; + } + + public function LoadTree(details) + { + this.root = new RectangleNode(0, 0, 0, 0, this); + root.ReadJSON(details); + + this.NextAllocationID = 0; + this.area = 0; + + var queue:Array = new Array(); + queue.push(root); + while (queue.length > 0) + { + var node:RectangleNode = queue.shift(); + node.AllocationID = NextAllocationID; + node.MinAllocationID = NextAllocationID; + if (node.Left) queue.push(node.Left); + if (node.Right) queue.push(node.Right); + if (node.InUse) this.area += node.Rect.width * node.Rect.height; + } + NextAllocationID++; + } + + public function GetNodePath(node:RectangleNode) + { + var output:String = ""; + while (node != this.root) + { + output = (node == node.Parent.Left ? "l" : "r") + output; + node = node.Parent; + } + return output; + } + + public function GetNodeFromPath(path:String):RectangleNode + { + var node:RectangleNode = this.root; + for (var i = 0; i < path.length; i++) + { + if (!node) return null; + if (path.charAt(i) == "r") + { + node = node.Right; + } else { + node = node.Left; + } + } + return node; + } + } +} diff --git a/flash/util/Utils.as b/flash/util/Utils.as new file mode 100644 index 0000000..f792003 --- /dev/null +++ b/flash/util/Utils.as @@ -0,0 +1,389 @@ +package util +{ + import flash.display.*; + import flash.geom.*; + public class Utils + { + public static function GetChildren(clip:MovieClip):Array + { + var ret:Array = []; + for (var i = 0; i < clip.numChildren; i++) + { + ret.push(clip.getChildAt(i)); + } + return ret; + } + + /* + * angle difference + * (range -Math.PI to Math.PI) + */ + public static function GetAngleDiff(a, b) + { + var angleDiff = b - a; + + while (angleDiff > Math.PI) + { + angleDiff -= Math.PI * 2; + } + while (angleDiff < -Math.PI) + { + angleDiff += Math.PI * 2; + } + return angleDiff; + } + + /* + * angle difference + * (range 0 to Math.PI) + */ + public static function GetAngleDiffAbs(a, b) + { + var angleDiff = GetAngleDiff(a, b); + while (angleDiff < 0) + { + angleDiff += Math.PI * 2; + } + + if (angleDiff > Math.PI) + { + angleDiff = Math.PI * 2 - angleDiff; + } + + return angleDiff; + } + + public static function GetTransform(from:Matrix, to:Matrix) + { + var i:Matrix = from.clone(); + i.invert(); + var m:Matrix = to.clone(); + m.concat(i); + return m; + } + + public static function Decompose(m:Matrix) + { + var s:Point = ScaleFromMat(m); + m = m.clone(); + + var sxUnit = s.x >= 0 ? 1 : -1; + var syUnit = s.y >= 0 ? 1 : -1; + + m.scale(sxUnit, syUnit); + + //m.a /= sxUnit; + //m.d /= syUnit; + var rot = RotFromMat(m); + return {sx:s.x, sy:s.y, rot:rot}; + } + + public static function RotFromMat(m:Matrix) + { + return Math.atan2(-m.c, m.a); + } + + public static function ScaleFromMat(m:Matrix):Point + { + var xAxisX = m.a; + var xAxisY = m.c; + + var yAxisX = m.b; + var yAxisY = m.d; + + var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); + if (m.a < 0) sx *= -1; + + var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); + if (m.d < 0) sy *= -1; + + return new Point(sx, sy); + } + + public static function TransformRect(r:Rectangle, m:Matrix) + { + var p1:Point = new Point(r.left, r.top); + var p2:Point = new Point(r.right, r.top); + var p3:Point = new Point(r.left, r.bottom); + var p4:Point = new Point(r.right, r.bottom); + + p1 = m.transformPoint(p1); + p2 = m.transformPoint(p2); + p3 = m.transformPoint(p3); + p4 = m.transformPoint(p4); + + r.left = Math.min(p1.x, p2.x, p3.x, p4.x); + r.top = Math.min(p1.y, p2.y, p3.y, p4.y); + r.right = Math.max(p1.x, p2.x, p3.x, p4.x); + r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); + } + + public static function RoundRect(r:Rectangle) + { + r.left = Math.floor(r.left); + r.top = Math.floor(r.top); + r.right = Math.ceil(r.right); + r.bottom = Math.ceil(r.bottom); + } + + public static function ScaleRect(r:Rectangle, s) + { + r.left *= s; + r.top *= s; + r.right *= s; + r.bottom *= s; + } + + public static function RecursivelyStop(clip) + { + if (clip is MovieClip) + { + clip.stop(); + } + if (clip is DisplayObjectContainer) + { + for (var i = 0; i < clip.numChildren; i++) + { + RecursivelyStop(clip.getChildAt(i)); + } + } + } + + public static function WeirdGotoFrame(clip:MovieClip, frame) + { + var dir = clip.currentFrame > frame ? -1 : 1; + while (clip.currentFrame != frame) + { + RecurseDir(clip, dir); + } + } + + protected static function RecurseDir(clip:MovieClip, dir) + { + for (var i = 0; i < clip.numChildren; i++) + { + var child = clip.getChildAt(i); + if (child is MovieClip) + { + RecurseDir(child, dir); + } + } + if (dir == 1) + { + clip.nextFrame(); + } else { + clip.prevFrame(); + } + } + + protected static var tempSpace:BitmapData = null; + protected static var tempSpaceRect:Rectangle = new Rectangle(); + protected static var tempSpaceMatrix:Matrix = new Matrix(); + protected static var tempSpaceZero:Point = new Point(); + protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); + protected static var lastDrawOffset:Point = new Point(); + public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle + { + if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); + + var oldPad = 0; + var padAmount = 5; + + var ret:Rectangle = new Rectangle(); + + var baseBounds:Rectangle = clip.getBounds(clip); + + var boundsClip:DisplayObject = null; + if (clip is DisplayObjectContainer) + { + boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); + } + + if (boundsClip != null) + { + baseBounds = boundsClip.getBounds(clip); + } + + if (useMatrix) + { + TransformAABBRect(baseBounds, useMatrix); + } + + if (boundsClip != null) + { + return baseBounds; + } + + var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); + var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); + if (tempSpace == null) + { + tempSpace = new BitmapData(minW, minH, true, 0x0); + } + if (tempSpace.width < minW || tempSpace.height < minH) + { + tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); + } + + var r:Rectangle = new Rectangle(); + + baseBounds.left = Math.floor(baseBounds.left); + baseBounds.right = Math.ceil(baseBounds.right); + + baseBounds.top = Math.floor(baseBounds.top); + baseBounds.bottom = Math.ceil(baseBounds.bottom); + + var i; + + var needsChecking = true; + while (needsChecking) + { + needsChecking = false; + r.left = baseBounds.left - padAmount; + r.right = baseBounds.right + padAmount; + + r.top = baseBounds.top - padAmount; + r.bottom = baseBounds.bottom + padAmount; + + ret = r.clone(); + + tempSpaceRect.x = tempSpaceRect.y = 0; + tempSpaceRect.width = tempSpace.width; + tempSpaceRect.height = tempSpace.height; + tempSpace.fillRect(tempSpaceRect, 0x0); + + tempSpaceMatrix.identity(); + if (useMatrix) + { + tempSpaceMatrix.a = useMatrix.a; + tempSpaceMatrix.b = useMatrix.b; + tempSpaceMatrix.c = useMatrix.c; + tempSpaceMatrix.d = useMatrix.d; + tempSpaceMatrix.tx = useMatrix.tx; + tempSpaceMatrix.ty = useMatrix.ty; + } + tempSpaceMatrix.translate(-r.left, -r.top); + + lastDrawOffset.x = -r.left; + lastDrawOffset.y = -r.top; + tempSpace.draw(clip, tempSpaceMatrix); + + tempSpaceRect.width = 1; + tempSpaceRect.height = r.height; + + var sideMovedIn = 0; + for (i = 0; i < r.width; i++) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.left++; + sideMovedIn++; + } + } + if (ret.left < baseBounds.left - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.width - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.right--; + } + } + if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + sideMovedIn = 0; + tempSpaceRect.width = r.width; + tempSpaceRect.height = 1; + tempSpaceRect.x = 0; + for (i = 0; i < r.height; i++) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.top++; + sideMovedIn++; + } + } + if (ret.top < baseBounds.top - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.height - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.bottom--; + } + } + if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + } + return ret; + } + + public static function TransformAABBRect(r:Rectangle, m:Matrix) + { + var o1X = r.left; + var o1Y = r.top; + + var o2X = r.right; + var o2Y = r.top; + + var o3X = r.left; + var o3Y = r.bottom; + + var o4X = r.right; + var o4Y = r.bottom; + + var n1X = o1X * m.a + o1Y * m.c + m.tx; + var n1Y = o1X * m.b + o1Y * m.d + m.ty; + + var n2X = o2X * m.a + o2Y * m.c + m.tx; + var n2Y = o2X * m.b + o2Y * m.d + m.ty; + + var n3X = o3X * m.a + o3Y * m.c + m.tx; + var n3Y = o3X * m.b + o3Y * m.d + m.ty; + + var n4X = o4X * m.a + o4Y * m.c + m.tx; + var n4Y = o4X * m.b + o4Y * m.d + m.ty; + + r.left = Math.min(n1X, n2X, n3X, n4X); + r.right = Math.max(n1X, n2X, n3X, n4X); + + r.top = Math.min(n1Y, n2Y, n3Y, n4Y); + r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); + } + } +} diff --git a/job.py b/job.py index 989c991..77c09e8 100644 --- a/job.py +++ b/job.py @@ -3,6 +3,7 @@ import json from validate import * from args import * +import copy asset_src_schema = { "type":"object", @@ -69,19 +70,24 @@ base_path = os.path.join(self.out_dir, self.rel_path) if not os.path.exists(base_path): os.makedirs(base_path) + resource_names = [] for i,r in enumerate(resources): - path = os.path.join(base_path, "%s_%04d.png" % (self.name, i)) + resource_name = "%s_%04d.png" % (self.name, i) if len(resources) > 1 else self.name + ".png" + resource_names.append(resource_name) + path = os.path.join(base_path, resource_name) with open(path, "wb") as f: f.write(base64.b64decode(r)) if len(data) == 1: graphic_and_asset = {} (name, graphic_data) = data.items()[0] - graphic_and_asset = {"data":graphic_data} + graphic_and_asset = {"data":graphic_data, "resources":resource_names} with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps(graphic_and_asset)) else: + write_data = copy.deepcopy(data) + write_data["resources"] = resource_names with open(os.path.join(base_path, self.name + ".asset"), "w") as f: - f.write(pretty_dumps(data)) + f.write(pretty_dumps(write_data)) for name,details in data.iteritems(): with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps({"data":self.name + ".asset"})) diff --git a/old/Checkbox.as b/old/Checkbox.as deleted file mode 100644 index c5aaba2..0000000 --- a/old/Checkbox.as +++ /dev/null @@ -1,42 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - - public class Checkbox extends MovieClip - { - public var Enabled:Boolean = true; - public function Checkbox() - { - checkbox.gotoAndStop(1); - checkbox.addEventListener(MouseEvent.CLICK, Clicked); - } - - protected function Clicked(event) - { - if (!Enabled) return; - Toggle(); - if (OnClick != null) OnClick(OnClickParam); - } - - protected var checked = false; - public function set Checked(value) { checked = value; checkbox.gotoAndStop(checked ? 2 : 1); } - public function get Checked() { return checked; } - - public function set Text(value) { text.text = value; } - - public var OnClickParam; - public var OnClick; - - - public function Toggle() - { - checked = !checked; - checkbox.gotoAndStop(checked ? 2 : 1); - - - } - - } - -} diff --git a/old/GraphicExport-app.xml b/old/GraphicExport-app.xml deleted file mode 100644 index 5144634..0000000 --- a/old/GraphicExport-app.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - GraphicExport - 1.0 - GraphicExport - - GraphicExport - - - GraphicExport.swf - standard - false - true - false - portrait - auto - true - true - true - - - false - false - desktop extendedDesktop diff --git a/old/GraphicExport.exe b/old/GraphicExport.exe deleted file mode 100644 index 56315aa..0000000 --- a/old/GraphicExport.exe +++ /dev/null Binary files differ diff --git a/old/GraphicExport.fla b/old/GraphicExport.fla deleted file mode 100644 index 0b78ed7..0000000 --- a/old/GraphicExport.fla +++ /dev/null Binary files differ diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/flash/util/RectangleNode.as b/flash/util/RectangleNode.as new file mode 100644 index 0000000..6f31e44 --- /dev/null +++ b/flash/util/RectangleNode.as @@ -0,0 +1,178 @@ +package util { + import flash.geom.Rectangle; + + public class RectangleNode + { + public var Left:RectangleNode = null; + public var Right:RectangleNode = null; + public var Rect:Rectangle = null; + public var InUse:Boolean = false; + public var Removed:Boolean = false; + public var Parent:RectangleNode = null; + public var AllocationID = 0; + public var Host:RectanglePacker= null; + public var MinAllocationID = 0; + public var NodeID; + public static var NextNodeID = 0; + + public var DontRemove = false; + + public var LastAccessTime = 0; + + public var Flags = []; + + public var UpdateTo:RectangleNode = null; + + /* + public function get Removed() + { + return _Removed; + } + + public function set Removed(r) + { + this._Removed = r; + } + + public function get Host():RectanglePacker + { + return _Host; + } + public function set Host(p:RectanglePacker) + { + this._Host = p; + + if (_Left && _Left.Host != p) + { + throw new Error("bad left host"); + } + if (_Right && _Right.Host != p) + { + throw new Error("bad right host"); + } + if (_Parent && _Parent.Host != p) + { + throw new Error("bad parent host"); + } + + } + + public function get Left():RectangleNode + { + return _Left; + } + public function set Left(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad left host"); + } + _Left = n; + } + public function get Right():RectangleNode + { + return _Right; + } + public function set Right(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad right host"); + } + _Right = n; + } + + public function get Parent():RectangleNode + { + return _Parent; + } + public function set Parent(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad parent host"); + } + _Parent = n; + } + */ + public function get IsFreeSpace() + { + return Left == null && Right == null && !InUse; + } + public function UpdateLinksFromNode(node:RectangleNode) + { + if (node.Parent) + { + if (node.Parent.Left == node) + { + node.Parent.Left = this; + } + if (node.Parent.Right == node) + { + node.Parent.Right = this; + } + } + if (node.Left) + { + node.Left.Parent = this; + } + if (node.Right) + { + node.Right.Parent = this; + } + } + public function MakeFromNode(node:RectangleNode) + { + //_Host = node.Host; + Host = node.Host; + Left = node.Left; + Right = node.Right; + Parent = node.Parent; + AllocationID = node.AllocationID; + InUse = node.InUse; + MinAllocationID = node.MinAllocationID; + NodeID = node.NodeID; + Rect = node.Rect.clone(); + Removed = node.Removed; + DontRemove = node.DontRemove; + } + public function RectangleNode(x, y, w, h, host:RectanglePacker) + { + this.NodeID = NextNodeID++; + this.Host = host; + this.Rect = new Rectangle(x, y, w, h); + } + public function OutputJSON() + { + var node = {}; + node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; + node.in_use = InUse; + node.id = NodeID; + if (this.Left) node.left = this.Left.OutputJSON(); + if (this.Right) node.right = this.Right.OutputJSON(); + return node; + } + + public function ReadJSON(details) + { + details.new_node = this; + this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); + this.Removed = false; + + this.InUse = details.in_use; + + if (details.hasOwnProperty("right")) + { + this.Right = new RectangleNode(0, 0, 0, 0, this.Host); + Right.ReadJSON(details.right); + Right.Parent = this; + } + if (details.hasOwnProperty("left")) + { + this.Left = new RectangleNode(0, 0, 0, 0, this.Host); + Left.ReadJSON(details.left); + Left.Parent = this; + } + } + } +} diff --git a/flash/util/RectanglePacker.as b/flash/util/RectanglePacker.as new file mode 100644 index 0000000..597d7fd --- /dev/null +++ b/flash/util/RectanglePacker.as @@ -0,0 +1,562 @@ +package util { + import flash.geom.*; + import flash.display.BitmapData; + import flash.display.MovieClip; + import flash.text.TextField; + import flash.events.*; + import flash.sampler.StackFrame; + + public class RectanglePacker + { + protected var w:int; + protected var h:int; + protected var root:RectangleNode; + public var NextAllocationID = 0; + + public function get width():int { return w; } + public function get height():int { return h; } + + public function RectanglePacker(w, h) + { + this.w = w; + this.h = h; + root = new RectangleNode(0, 0, w, h, this); + root.AllocationID = -1; + } + protected var area = 0; + + protected var testRender:MovieClip = new MovieClip(); + + public function GetRoot():RectangleNode + { + return root; + } + + public function GetLeafNodes():Array + { + return GetLeafNodesInternal(root); + } + + protected function GetLeafNodesInternal(n:RectangleNode):Array + { + if (n.InUse) return [n]; + var ret:Array = new Array(); + if (n.Left) ret = GetLeafNodesInternal(n.Left); + if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); + return ret; + } + + public function GetUsedArea() + { + return area; + } + + public function get efficiency() + { + return area / (w * h); + } + + protected function RectCost(w, h) + { + if (w == 0 || h == 0) return 99999999; + return (Math.max(w, h) / Math.min(w, h)) * w * h; + } + + protected function EnumerateTree(r:RectangleNode = null, indent = "") + { + if (r == null) r = this.root; + var str = ""; + str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; + if (r.Left) str += EnumerateTree(r.Left, indent + " "); + if (r.Right) str += EnumerateTree(r.Left, indent + " "); + return str; + } + + /* + * Remove a list of nodes from the tree. + * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree + * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, + leaving the original objects intact (in case something still references them) + */ + public function RemoveNodes(nodes:Array, fullyDestroy = true) + { + + /* DEBUG CHECKS */ + /* + this.PerformDebugCheck(); + + var str = ""; + for (var i = 0; i < nodes.length; i++) + { + str += nodes[i].NodeID + "\n"; + } + + var orig = nodes.concat(); + + var strs = [str, EnumerateTree()]; + + RenderDetailsBox.StartTrack("PackRemoveTime"); + + for (var i = 0; i < nodes.length; i++) + { + var n:RectangleNode = nodes[i]; + if (n.Host != this) + { + throw new Error("bad host!"); + } + } + */ + /* END DEBUG CHECKS */ + + var i, n:RectangleNode, p:RectangleNode; + + // setup the Removed flag on every node that should be removed + // we also check at this time to see if any more nodes need to be removed, such as a parent of + // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + if (n.Host == this) + { + n.Removed = true; + + if (n.InUse) + { + // sum up the total removed area + area -= n.Rect.width * n.Rect.height; + } + + if (n.Parent != null) + { + p = n.Parent; + // check and see if the current node's parent still has any valid children + if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) + { + // all of the current nodes siblings are either being removed or are blank, so + // we can remove the parent too + if (p.Left.IsFreeSpace) + { + // the left child was empty space before, so we can remove it (if it wasn't + // empty space it is already being removed so it doesn't need to be added + // to the list) + if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); + } + if (p.Right.IsFreeSpace) + { + // the right child was empty space before, so we can remove it + if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); + } + if (p != root && nodes.indexOf(p) == -1) + { + // remove the parent node too (provided it isn't the root!) + nodes.push(p); + } + } + } + } + } + + // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, + // so go ahead and remove them + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + + if (n.Parent != null) + { + // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not + // also getting removed!) + p = n.Parent; + + if (!p.Removed) + { + if (p.Left && p.Right) + { + var newNode:RectangleNode; + if (p.Left.Removed && p.Right.Removed) + { + // both children were removed, but the parent wasn't, so the parent must be root + // (since we never remove the root) + if (p != root) + { + throw new Error("should be root"); + } + p.Left.Parent = null; + p.Right.Parent = null; + p.Left = null; + p.Right = null; + p.InUse = false; + } else if (!p.Left.Removed) { + // Right node removed, Left node not removed + if (!p.Left.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Right); + newNode.UpdateLinksFromNode(p.Right); + } + // Left node is used + p.Right.InUse = false; + p.Right.Left = null; + p.Right.Right = null; + p.Right.Removed = false; + } else { + throw new Error("should have been caught above!"); + } + } else { + // Left node removed, Right node not removed + if (!p.Right.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Left); + newNode.UpdateLinksFromNode(p.Left); + } + // Left node is used + //p.Left.Removed = true; + p.Left.InUse = false; + p.Left.Left = null; + p.Left.Right = null; + p.Left.Removed = false; + //p.Left.Parent = null; + } else { + throw new Error("should have been caught above!"); + } + } + } else { + // huh? how does n.Parent == p but p has no children? something went wrong + throw new Error("shouldn't have gotten here"); + } + } + } + //strs.push(EnumerateTree()); + } + } + + public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode + { + + var node:RectangleNode = FindSizedNode(w, h, root); + + if (node == null) + { + //UHOH, texture full + return null; + } + area += w * h; + node.InUse = true; + + var splitVertFirstCost = 0; + if (w < node.Rect.width) + { + splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); + } + + var splitHorizFirstCost = 0; + if (h < node.Rect.height) + { + splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); + } + + + + if (splitVertFirstCost <= splitHorizFirstCost) + { + node.Flags.push("SplitVertFirst"); + if (w < node.Rect.width) + { + node.Flags.push("SplitVert"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + if (h < node.Rect.height) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + } else { + node.Flags.push("SplitHorzFirst"); + if (h < node.Rect.height) + { + node.Flags.push("SplitVert"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + if (w < node.Rect.width) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + } + NextAllocationID++; + if (useInstead) + { + useInstead.MakeFromNode(node); + useInstead.UpdateLinksFromNode(node); + useInstead.Flags = node.Flags; + node = useInstead; + node.Flags.push("UseInstead"); + } + + //if (!CheckOKNode(node)) node.Flags.push("BadNode"); + + return node; + } + public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) + { + if (r == null) r = this.root; + if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) + { + var ancestor:RectangleNode = FindCommonNode(n, r); + throw new Error("bad node allocated!"); + return false; + } + var ok = true; + if (r.Left) ok = ok && CheckOKNode(n, r.Left); + if (r.Right) ok = ok && CheckOKNode(n, r.Right); + return ok; + } + + public function PerformDebugCheck() + { + DebugInternal(this.root); + } + + protected function DebugInternal(n:RectangleNode) + { + if (n.Host != this) + { + throw new Error("problem with host!"); + } + if (n.IsFreeSpace) + { + if (n.Left || n.Right) + { + throw new Error("shouldn't have children"); + } + } + if ((n.Left && !n.Right) || (n.Right && !n.Left)) + { + throw new Error("mismatched children"); + } + if (n.Left && n.Left.Parent != n) + { + throw new Error("left child has bad parent"); + } + if (n.Right && n.Right.Parent != n) + { + throw new Error("right child has bad parent"); + } + if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) + { + throw new Error("problem with parent"); + } + if (n.Left) DebugInternal(n.Left); + if (n.Right) DebugInternal(n.Right); + } + + public function FindCommonNode(a:RectangleNode, b:RectangleNode) + { + var aHistory = []; + var bHistory = []; + while (a != null) + { + aHistory.push(a); + a = a.Parent; + } + while (b != null) + { + bHistory.push(b); + b = b.Parent; + } + var i = aHistory.length - 1; + var j = bHistory.length - 1; + var same = null; + while (i >= 0 && j >= 0) + { + if (aHistory[i] == bHistory[j]) + { + same = aHistory[i]; + } else { + break; + } + i--; + j--; + } + return same; + } + + public function TestRender() + { + while (testRender.numChildren > 0) + { + testRender.removeChildAt(0); + } + testRender.graphics.clear(); + TestRenderNode(root, testRender); + return testRender; + } + protected function TestRenderNode(n:RectangleNode, m:MovieClip) + { + var g:MovieClip = new MovieClip(); + m.addChild(g); + g.graphics.lineStyle(1, 0, 1); + if (n.Left != null) TestRenderNode(n.Left, m); + if (n.Left != null) TestRenderNode(n.Right, m); + if (n.InUse) + { + g.graphics.beginFill(0xFFFF00, 0.2); + } + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + if (n.InUse) + { + g.graphics.endFill(); + var t:TextField = new TextField(); + t.text = n.NodeID; + t.x = n.Rect.x + n.Rect.width / 2.0; + t.y = n.Rect.y + n.Rect.height / 2.0; + g.addChild(t); + g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); + g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); + } + + } + public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) + { + if (n.InUse) + { + //_trace(Math.round(n.LastAccessTime / 1000)); + } + var p:RectangleNode = n.Parent; + if (p) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); + g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); + g.graphics.endFill(); + t.text = p.NodeID; + if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); + g.oldListener = function(e){MouseOver(p, g, t);}; + g.addEventListener(MouseEvent.CLICK, g.oldListener); + } + } + public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(0xFFFF00, 0.2); + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + g.graphics.endFill(); + t.text = n.NodeID; + } + protected function SplitVert(node:RectangleNode, leftWidth) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function SplitHoriz(node:RectangleNode, topHeight) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode + { + if (node.InUse) return null; + if (node.Rect.width >= w && node.Rect.height >= h) + { + if (node.Left != null && node.Right != null) + { + var t:RectangleNode = FindSizedNode(w, h, node.Left); + if (t != null) return t; + t = FindSizedNode(w, h, node.Right); + return t; + } else { + return node; + } + } + return null; + } + + public function LoadTree(details) + { + this.root = new RectangleNode(0, 0, 0, 0, this); + root.ReadJSON(details); + + this.NextAllocationID = 0; + this.area = 0; + + var queue:Array = new Array(); + queue.push(root); + while (queue.length > 0) + { + var node:RectangleNode = queue.shift(); + node.AllocationID = NextAllocationID; + node.MinAllocationID = NextAllocationID; + if (node.Left) queue.push(node.Left); + if (node.Right) queue.push(node.Right); + if (node.InUse) this.area += node.Rect.width * node.Rect.height; + } + NextAllocationID++; + } + + public function GetNodePath(node:RectangleNode) + { + var output:String = ""; + while (node != this.root) + { + output = (node == node.Parent.Left ? "l" : "r") + output; + node = node.Parent; + } + return output; + } + + public function GetNodeFromPath(path:String):RectangleNode + { + var node:RectangleNode = this.root; + for (var i = 0; i < path.length; i++) + { + if (!node) return null; + if (path.charAt(i) == "r") + { + node = node.Right; + } else { + node = node.Left; + } + } + return node; + } + } +} diff --git a/flash/util/Utils.as b/flash/util/Utils.as new file mode 100644 index 0000000..f792003 --- /dev/null +++ b/flash/util/Utils.as @@ -0,0 +1,389 @@ +package util +{ + import flash.display.*; + import flash.geom.*; + public class Utils + { + public static function GetChildren(clip:MovieClip):Array + { + var ret:Array = []; + for (var i = 0; i < clip.numChildren; i++) + { + ret.push(clip.getChildAt(i)); + } + return ret; + } + + /* + * angle difference + * (range -Math.PI to Math.PI) + */ + public static function GetAngleDiff(a, b) + { + var angleDiff = b - a; + + while (angleDiff > Math.PI) + { + angleDiff -= Math.PI * 2; + } + while (angleDiff < -Math.PI) + { + angleDiff += Math.PI * 2; + } + return angleDiff; + } + + /* + * angle difference + * (range 0 to Math.PI) + */ + public static function GetAngleDiffAbs(a, b) + { + var angleDiff = GetAngleDiff(a, b); + while (angleDiff < 0) + { + angleDiff += Math.PI * 2; + } + + if (angleDiff > Math.PI) + { + angleDiff = Math.PI * 2 - angleDiff; + } + + return angleDiff; + } + + public static function GetTransform(from:Matrix, to:Matrix) + { + var i:Matrix = from.clone(); + i.invert(); + var m:Matrix = to.clone(); + m.concat(i); + return m; + } + + public static function Decompose(m:Matrix) + { + var s:Point = ScaleFromMat(m); + m = m.clone(); + + var sxUnit = s.x >= 0 ? 1 : -1; + var syUnit = s.y >= 0 ? 1 : -1; + + m.scale(sxUnit, syUnit); + + //m.a /= sxUnit; + //m.d /= syUnit; + var rot = RotFromMat(m); + return {sx:s.x, sy:s.y, rot:rot}; + } + + public static function RotFromMat(m:Matrix) + { + return Math.atan2(-m.c, m.a); + } + + public static function ScaleFromMat(m:Matrix):Point + { + var xAxisX = m.a; + var xAxisY = m.c; + + var yAxisX = m.b; + var yAxisY = m.d; + + var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); + if (m.a < 0) sx *= -1; + + var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); + if (m.d < 0) sy *= -1; + + return new Point(sx, sy); + } + + public static function TransformRect(r:Rectangle, m:Matrix) + { + var p1:Point = new Point(r.left, r.top); + var p2:Point = new Point(r.right, r.top); + var p3:Point = new Point(r.left, r.bottom); + var p4:Point = new Point(r.right, r.bottom); + + p1 = m.transformPoint(p1); + p2 = m.transformPoint(p2); + p3 = m.transformPoint(p3); + p4 = m.transformPoint(p4); + + r.left = Math.min(p1.x, p2.x, p3.x, p4.x); + r.top = Math.min(p1.y, p2.y, p3.y, p4.y); + r.right = Math.max(p1.x, p2.x, p3.x, p4.x); + r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); + } + + public static function RoundRect(r:Rectangle) + { + r.left = Math.floor(r.left); + r.top = Math.floor(r.top); + r.right = Math.ceil(r.right); + r.bottom = Math.ceil(r.bottom); + } + + public static function ScaleRect(r:Rectangle, s) + { + r.left *= s; + r.top *= s; + r.right *= s; + r.bottom *= s; + } + + public static function RecursivelyStop(clip) + { + if (clip is MovieClip) + { + clip.stop(); + } + if (clip is DisplayObjectContainer) + { + for (var i = 0; i < clip.numChildren; i++) + { + RecursivelyStop(clip.getChildAt(i)); + } + } + } + + public static function WeirdGotoFrame(clip:MovieClip, frame) + { + var dir = clip.currentFrame > frame ? -1 : 1; + while (clip.currentFrame != frame) + { + RecurseDir(clip, dir); + } + } + + protected static function RecurseDir(clip:MovieClip, dir) + { + for (var i = 0; i < clip.numChildren; i++) + { + var child = clip.getChildAt(i); + if (child is MovieClip) + { + RecurseDir(child, dir); + } + } + if (dir == 1) + { + clip.nextFrame(); + } else { + clip.prevFrame(); + } + } + + protected static var tempSpace:BitmapData = null; + protected static var tempSpaceRect:Rectangle = new Rectangle(); + protected static var tempSpaceMatrix:Matrix = new Matrix(); + protected static var tempSpaceZero:Point = new Point(); + protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); + protected static var lastDrawOffset:Point = new Point(); + public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle + { + if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); + + var oldPad = 0; + var padAmount = 5; + + var ret:Rectangle = new Rectangle(); + + var baseBounds:Rectangle = clip.getBounds(clip); + + var boundsClip:DisplayObject = null; + if (clip is DisplayObjectContainer) + { + boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); + } + + if (boundsClip != null) + { + baseBounds = boundsClip.getBounds(clip); + } + + if (useMatrix) + { + TransformAABBRect(baseBounds, useMatrix); + } + + if (boundsClip != null) + { + return baseBounds; + } + + var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); + var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); + if (tempSpace == null) + { + tempSpace = new BitmapData(minW, minH, true, 0x0); + } + if (tempSpace.width < minW || tempSpace.height < minH) + { + tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); + } + + var r:Rectangle = new Rectangle(); + + baseBounds.left = Math.floor(baseBounds.left); + baseBounds.right = Math.ceil(baseBounds.right); + + baseBounds.top = Math.floor(baseBounds.top); + baseBounds.bottom = Math.ceil(baseBounds.bottom); + + var i; + + var needsChecking = true; + while (needsChecking) + { + needsChecking = false; + r.left = baseBounds.left - padAmount; + r.right = baseBounds.right + padAmount; + + r.top = baseBounds.top - padAmount; + r.bottom = baseBounds.bottom + padAmount; + + ret = r.clone(); + + tempSpaceRect.x = tempSpaceRect.y = 0; + tempSpaceRect.width = tempSpace.width; + tempSpaceRect.height = tempSpace.height; + tempSpace.fillRect(tempSpaceRect, 0x0); + + tempSpaceMatrix.identity(); + if (useMatrix) + { + tempSpaceMatrix.a = useMatrix.a; + tempSpaceMatrix.b = useMatrix.b; + tempSpaceMatrix.c = useMatrix.c; + tempSpaceMatrix.d = useMatrix.d; + tempSpaceMatrix.tx = useMatrix.tx; + tempSpaceMatrix.ty = useMatrix.ty; + } + tempSpaceMatrix.translate(-r.left, -r.top); + + lastDrawOffset.x = -r.left; + lastDrawOffset.y = -r.top; + tempSpace.draw(clip, tempSpaceMatrix); + + tempSpaceRect.width = 1; + tempSpaceRect.height = r.height; + + var sideMovedIn = 0; + for (i = 0; i < r.width; i++) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.left++; + sideMovedIn++; + } + } + if (ret.left < baseBounds.left - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.width - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.right--; + } + } + if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + sideMovedIn = 0; + tempSpaceRect.width = r.width; + tempSpaceRect.height = 1; + tempSpaceRect.x = 0; + for (i = 0; i < r.height; i++) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.top++; + sideMovedIn++; + } + } + if (ret.top < baseBounds.top - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.height - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.bottom--; + } + } + if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + } + return ret; + } + + public static function TransformAABBRect(r:Rectangle, m:Matrix) + { + var o1X = r.left; + var o1Y = r.top; + + var o2X = r.right; + var o2Y = r.top; + + var o3X = r.left; + var o3Y = r.bottom; + + var o4X = r.right; + var o4Y = r.bottom; + + var n1X = o1X * m.a + o1Y * m.c + m.tx; + var n1Y = o1X * m.b + o1Y * m.d + m.ty; + + var n2X = o2X * m.a + o2Y * m.c + m.tx; + var n2Y = o2X * m.b + o2Y * m.d + m.ty; + + var n3X = o3X * m.a + o3Y * m.c + m.tx; + var n3Y = o3X * m.b + o3Y * m.d + m.ty; + + var n4X = o4X * m.a + o4Y * m.c + m.tx; + var n4Y = o4X * m.b + o4Y * m.d + m.ty; + + r.left = Math.min(n1X, n2X, n3X, n4X); + r.right = Math.max(n1X, n2X, n3X, n4X); + + r.top = Math.min(n1Y, n2Y, n3Y, n4Y); + r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); + } + } +} diff --git a/job.py b/job.py index 989c991..77c09e8 100644 --- a/job.py +++ b/job.py @@ -3,6 +3,7 @@ import json from validate import * from args import * +import copy asset_src_schema = { "type":"object", @@ -69,19 +70,24 @@ base_path = os.path.join(self.out_dir, self.rel_path) if not os.path.exists(base_path): os.makedirs(base_path) + resource_names = [] for i,r in enumerate(resources): - path = os.path.join(base_path, "%s_%04d.png" % (self.name, i)) + resource_name = "%s_%04d.png" % (self.name, i) if len(resources) > 1 else self.name + ".png" + resource_names.append(resource_name) + path = os.path.join(base_path, resource_name) with open(path, "wb") as f: f.write(base64.b64decode(r)) if len(data) == 1: graphic_and_asset = {} (name, graphic_data) = data.items()[0] - graphic_and_asset = {"data":graphic_data} + graphic_and_asset = {"data":graphic_data, "resources":resource_names} with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps(graphic_and_asset)) else: + write_data = copy.deepcopy(data) + write_data["resources"] = resource_names with open(os.path.join(base_path, self.name + ".asset"), "w") as f: - f.write(pretty_dumps(data)) + f.write(pretty_dumps(write_data)) for name,details in data.iteritems(): with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps({"data":self.name + ".asset"})) diff --git a/old/Checkbox.as b/old/Checkbox.as deleted file mode 100644 index c5aaba2..0000000 --- a/old/Checkbox.as +++ /dev/null @@ -1,42 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - - public class Checkbox extends MovieClip - { - public var Enabled:Boolean = true; - public function Checkbox() - { - checkbox.gotoAndStop(1); - checkbox.addEventListener(MouseEvent.CLICK, Clicked); - } - - protected function Clicked(event) - { - if (!Enabled) return; - Toggle(); - if (OnClick != null) OnClick(OnClickParam); - } - - protected var checked = false; - public function set Checked(value) { checked = value; checkbox.gotoAndStop(checked ? 2 : 1); } - public function get Checked() { return checked; } - - public function set Text(value) { text.text = value; } - - public var OnClickParam; - public var OnClick; - - - public function Toggle() - { - checked = !checked; - checkbox.gotoAndStop(checked ? 2 : 1); - - - } - - } - -} diff --git a/old/GraphicExport-app.xml b/old/GraphicExport-app.xml deleted file mode 100644 index 5144634..0000000 --- a/old/GraphicExport-app.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - GraphicExport - 1.0 - GraphicExport - - GraphicExport - - - GraphicExport.swf - standard - false - true - false - portrait - auto - true - true - true - - - false - false - desktop extendedDesktop diff --git a/old/GraphicExport.exe b/old/GraphicExport.exe deleted file mode 100644 index 56315aa..0000000 --- a/old/GraphicExport.exe +++ /dev/null Binary files differ diff --git a/old/GraphicExport.fla b/old/GraphicExport.fla deleted file mode 100644 index 0b78ed7..0000000 --- a/old/GraphicExport.fla +++ /dev/null Binary files differ diff --git a/old/GraphicExport.swf b/old/GraphicExport.swf deleted file mode 100644 index 542db97..0000000 --- a/old/GraphicExport.swf +++ /dev/null Binary files differ diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/flash/util/RectangleNode.as b/flash/util/RectangleNode.as new file mode 100644 index 0000000..6f31e44 --- /dev/null +++ b/flash/util/RectangleNode.as @@ -0,0 +1,178 @@ +package util { + import flash.geom.Rectangle; + + public class RectangleNode + { + public var Left:RectangleNode = null; + public var Right:RectangleNode = null; + public var Rect:Rectangle = null; + public var InUse:Boolean = false; + public var Removed:Boolean = false; + public var Parent:RectangleNode = null; + public var AllocationID = 0; + public var Host:RectanglePacker= null; + public var MinAllocationID = 0; + public var NodeID; + public static var NextNodeID = 0; + + public var DontRemove = false; + + public var LastAccessTime = 0; + + public var Flags = []; + + public var UpdateTo:RectangleNode = null; + + /* + public function get Removed() + { + return _Removed; + } + + public function set Removed(r) + { + this._Removed = r; + } + + public function get Host():RectanglePacker + { + return _Host; + } + public function set Host(p:RectanglePacker) + { + this._Host = p; + + if (_Left && _Left.Host != p) + { + throw new Error("bad left host"); + } + if (_Right && _Right.Host != p) + { + throw new Error("bad right host"); + } + if (_Parent && _Parent.Host != p) + { + throw new Error("bad parent host"); + } + + } + + public function get Left():RectangleNode + { + return _Left; + } + public function set Left(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad left host"); + } + _Left = n; + } + public function get Right():RectangleNode + { + return _Right; + } + public function set Right(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad right host"); + } + _Right = n; + } + + public function get Parent():RectangleNode + { + return _Parent; + } + public function set Parent(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad parent host"); + } + _Parent = n; + } + */ + public function get IsFreeSpace() + { + return Left == null && Right == null && !InUse; + } + public function UpdateLinksFromNode(node:RectangleNode) + { + if (node.Parent) + { + if (node.Parent.Left == node) + { + node.Parent.Left = this; + } + if (node.Parent.Right == node) + { + node.Parent.Right = this; + } + } + if (node.Left) + { + node.Left.Parent = this; + } + if (node.Right) + { + node.Right.Parent = this; + } + } + public function MakeFromNode(node:RectangleNode) + { + //_Host = node.Host; + Host = node.Host; + Left = node.Left; + Right = node.Right; + Parent = node.Parent; + AllocationID = node.AllocationID; + InUse = node.InUse; + MinAllocationID = node.MinAllocationID; + NodeID = node.NodeID; + Rect = node.Rect.clone(); + Removed = node.Removed; + DontRemove = node.DontRemove; + } + public function RectangleNode(x, y, w, h, host:RectanglePacker) + { + this.NodeID = NextNodeID++; + this.Host = host; + this.Rect = new Rectangle(x, y, w, h); + } + public function OutputJSON() + { + var node = {}; + node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; + node.in_use = InUse; + node.id = NodeID; + if (this.Left) node.left = this.Left.OutputJSON(); + if (this.Right) node.right = this.Right.OutputJSON(); + return node; + } + + public function ReadJSON(details) + { + details.new_node = this; + this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); + this.Removed = false; + + this.InUse = details.in_use; + + if (details.hasOwnProperty("right")) + { + this.Right = new RectangleNode(0, 0, 0, 0, this.Host); + Right.ReadJSON(details.right); + Right.Parent = this; + } + if (details.hasOwnProperty("left")) + { + this.Left = new RectangleNode(0, 0, 0, 0, this.Host); + Left.ReadJSON(details.left); + Left.Parent = this; + } + } + } +} diff --git a/flash/util/RectanglePacker.as b/flash/util/RectanglePacker.as new file mode 100644 index 0000000..597d7fd --- /dev/null +++ b/flash/util/RectanglePacker.as @@ -0,0 +1,562 @@ +package util { + import flash.geom.*; + import flash.display.BitmapData; + import flash.display.MovieClip; + import flash.text.TextField; + import flash.events.*; + import flash.sampler.StackFrame; + + public class RectanglePacker + { + protected var w:int; + protected var h:int; + protected var root:RectangleNode; + public var NextAllocationID = 0; + + public function get width():int { return w; } + public function get height():int { return h; } + + public function RectanglePacker(w, h) + { + this.w = w; + this.h = h; + root = new RectangleNode(0, 0, w, h, this); + root.AllocationID = -1; + } + protected var area = 0; + + protected var testRender:MovieClip = new MovieClip(); + + public function GetRoot():RectangleNode + { + return root; + } + + public function GetLeafNodes():Array + { + return GetLeafNodesInternal(root); + } + + protected function GetLeafNodesInternal(n:RectangleNode):Array + { + if (n.InUse) return [n]; + var ret:Array = new Array(); + if (n.Left) ret = GetLeafNodesInternal(n.Left); + if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); + return ret; + } + + public function GetUsedArea() + { + return area; + } + + public function get efficiency() + { + return area / (w * h); + } + + protected function RectCost(w, h) + { + if (w == 0 || h == 0) return 99999999; + return (Math.max(w, h) / Math.min(w, h)) * w * h; + } + + protected function EnumerateTree(r:RectangleNode = null, indent = "") + { + if (r == null) r = this.root; + var str = ""; + str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; + if (r.Left) str += EnumerateTree(r.Left, indent + " "); + if (r.Right) str += EnumerateTree(r.Left, indent + " "); + return str; + } + + /* + * Remove a list of nodes from the tree. + * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree + * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, + leaving the original objects intact (in case something still references them) + */ + public function RemoveNodes(nodes:Array, fullyDestroy = true) + { + + /* DEBUG CHECKS */ + /* + this.PerformDebugCheck(); + + var str = ""; + for (var i = 0; i < nodes.length; i++) + { + str += nodes[i].NodeID + "\n"; + } + + var orig = nodes.concat(); + + var strs = [str, EnumerateTree()]; + + RenderDetailsBox.StartTrack("PackRemoveTime"); + + for (var i = 0; i < nodes.length; i++) + { + var n:RectangleNode = nodes[i]; + if (n.Host != this) + { + throw new Error("bad host!"); + } + } + */ + /* END DEBUG CHECKS */ + + var i, n:RectangleNode, p:RectangleNode; + + // setup the Removed flag on every node that should be removed + // we also check at this time to see if any more nodes need to be removed, such as a parent of + // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + if (n.Host == this) + { + n.Removed = true; + + if (n.InUse) + { + // sum up the total removed area + area -= n.Rect.width * n.Rect.height; + } + + if (n.Parent != null) + { + p = n.Parent; + // check and see if the current node's parent still has any valid children + if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) + { + // all of the current nodes siblings are either being removed or are blank, so + // we can remove the parent too + if (p.Left.IsFreeSpace) + { + // the left child was empty space before, so we can remove it (if it wasn't + // empty space it is already being removed so it doesn't need to be added + // to the list) + if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); + } + if (p.Right.IsFreeSpace) + { + // the right child was empty space before, so we can remove it + if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); + } + if (p != root && nodes.indexOf(p) == -1) + { + // remove the parent node too (provided it isn't the root!) + nodes.push(p); + } + } + } + } + } + + // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, + // so go ahead and remove them + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + + if (n.Parent != null) + { + // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not + // also getting removed!) + p = n.Parent; + + if (!p.Removed) + { + if (p.Left && p.Right) + { + var newNode:RectangleNode; + if (p.Left.Removed && p.Right.Removed) + { + // both children were removed, but the parent wasn't, so the parent must be root + // (since we never remove the root) + if (p != root) + { + throw new Error("should be root"); + } + p.Left.Parent = null; + p.Right.Parent = null; + p.Left = null; + p.Right = null; + p.InUse = false; + } else if (!p.Left.Removed) { + // Right node removed, Left node not removed + if (!p.Left.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Right); + newNode.UpdateLinksFromNode(p.Right); + } + // Left node is used + p.Right.InUse = false; + p.Right.Left = null; + p.Right.Right = null; + p.Right.Removed = false; + } else { + throw new Error("should have been caught above!"); + } + } else { + // Left node removed, Right node not removed + if (!p.Right.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Left); + newNode.UpdateLinksFromNode(p.Left); + } + // Left node is used + //p.Left.Removed = true; + p.Left.InUse = false; + p.Left.Left = null; + p.Left.Right = null; + p.Left.Removed = false; + //p.Left.Parent = null; + } else { + throw new Error("should have been caught above!"); + } + } + } else { + // huh? how does n.Parent == p but p has no children? something went wrong + throw new Error("shouldn't have gotten here"); + } + } + } + //strs.push(EnumerateTree()); + } + } + + public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode + { + + var node:RectangleNode = FindSizedNode(w, h, root); + + if (node == null) + { + //UHOH, texture full + return null; + } + area += w * h; + node.InUse = true; + + var splitVertFirstCost = 0; + if (w < node.Rect.width) + { + splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); + } + + var splitHorizFirstCost = 0; + if (h < node.Rect.height) + { + splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); + } + + + + if (splitVertFirstCost <= splitHorizFirstCost) + { + node.Flags.push("SplitVertFirst"); + if (w < node.Rect.width) + { + node.Flags.push("SplitVert"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + if (h < node.Rect.height) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + } else { + node.Flags.push("SplitHorzFirst"); + if (h < node.Rect.height) + { + node.Flags.push("SplitVert"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + if (w < node.Rect.width) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + } + NextAllocationID++; + if (useInstead) + { + useInstead.MakeFromNode(node); + useInstead.UpdateLinksFromNode(node); + useInstead.Flags = node.Flags; + node = useInstead; + node.Flags.push("UseInstead"); + } + + //if (!CheckOKNode(node)) node.Flags.push("BadNode"); + + return node; + } + public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) + { + if (r == null) r = this.root; + if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) + { + var ancestor:RectangleNode = FindCommonNode(n, r); + throw new Error("bad node allocated!"); + return false; + } + var ok = true; + if (r.Left) ok = ok && CheckOKNode(n, r.Left); + if (r.Right) ok = ok && CheckOKNode(n, r.Right); + return ok; + } + + public function PerformDebugCheck() + { + DebugInternal(this.root); + } + + protected function DebugInternal(n:RectangleNode) + { + if (n.Host != this) + { + throw new Error("problem with host!"); + } + if (n.IsFreeSpace) + { + if (n.Left || n.Right) + { + throw new Error("shouldn't have children"); + } + } + if ((n.Left && !n.Right) || (n.Right && !n.Left)) + { + throw new Error("mismatched children"); + } + if (n.Left && n.Left.Parent != n) + { + throw new Error("left child has bad parent"); + } + if (n.Right && n.Right.Parent != n) + { + throw new Error("right child has bad parent"); + } + if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) + { + throw new Error("problem with parent"); + } + if (n.Left) DebugInternal(n.Left); + if (n.Right) DebugInternal(n.Right); + } + + public function FindCommonNode(a:RectangleNode, b:RectangleNode) + { + var aHistory = []; + var bHistory = []; + while (a != null) + { + aHistory.push(a); + a = a.Parent; + } + while (b != null) + { + bHistory.push(b); + b = b.Parent; + } + var i = aHistory.length - 1; + var j = bHistory.length - 1; + var same = null; + while (i >= 0 && j >= 0) + { + if (aHistory[i] == bHistory[j]) + { + same = aHistory[i]; + } else { + break; + } + i--; + j--; + } + return same; + } + + public function TestRender() + { + while (testRender.numChildren > 0) + { + testRender.removeChildAt(0); + } + testRender.graphics.clear(); + TestRenderNode(root, testRender); + return testRender; + } + protected function TestRenderNode(n:RectangleNode, m:MovieClip) + { + var g:MovieClip = new MovieClip(); + m.addChild(g); + g.graphics.lineStyle(1, 0, 1); + if (n.Left != null) TestRenderNode(n.Left, m); + if (n.Left != null) TestRenderNode(n.Right, m); + if (n.InUse) + { + g.graphics.beginFill(0xFFFF00, 0.2); + } + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + if (n.InUse) + { + g.graphics.endFill(); + var t:TextField = new TextField(); + t.text = n.NodeID; + t.x = n.Rect.x + n.Rect.width / 2.0; + t.y = n.Rect.y + n.Rect.height / 2.0; + g.addChild(t); + g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); + g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); + } + + } + public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) + { + if (n.InUse) + { + //_trace(Math.round(n.LastAccessTime / 1000)); + } + var p:RectangleNode = n.Parent; + if (p) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); + g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); + g.graphics.endFill(); + t.text = p.NodeID; + if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); + g.oldListener = function(e){MouseOver(p, g, t);}; + g.addEventListener(MouseEvent.CLICK, g.oldListener); + } + } + public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(0xFFFF00, 0.2); + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + g.graphics.endFill(); + t.text = n.NodeID; + } + protected function SplitVert(node:RectangleNode, leftWidth) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function SplitHoriz(node:RectangleNode, topHeight) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode + { + if (node.InUse) return null; + if (node.Rect.width >= w && node.Rect.height >= h) + { + if (node.Left != null && node.Right != null) + { + var t:RectangleNode = FindSizedNode(w, h, node.Left); + if (t != null) return t; + t = FindSizedNode(w, h, node.Right); + return t; + } else { + return node; + } + } + return null; + } + + public function LoadTree(details) + { + this.root = new RectangleNode(0, 0, 0, 0, this); + root.ReadJSON(details); + + this.NextAllocationID = 0; + this.area = 0; + + var queue:Array = new Array(); + queue.push(root); + while (queue.length > 0) + { + var node:RectangleNode = queue.shift(); + node.AllocationID = NextAllocationID; + node.MinAllocationID = NextAllocationID; + if (node.Left) queue.push(node.Left); + if (node.Right) queue.push(node.Right); + if (node.InUse) this.area += node.Rect.width * node.Rect.height; + } + NextAllocationID++; + } + + public function GetNodePath(node:RectangleNode) + { + var output:String = ""; + while (node != this.root) + { + output = (node == node.Parent.Left ? "l" : "r") + output; + node = node.Parent; + } + return output; + } + + public function GetNodeFromPath(path:String):RectangleNode + { + var node:RectangleNode = this.root; + for (var i = 0; i < path.length; i++) + { + if (!node) return null; + if (path.charAt(i) == "r") + { + node = node.Right; + } else { + node = node.Left; + } + } + return node; + } + } +} diff --git a/flash/util/Utils.as b/flash/util/Utils.as new file mode 100644 index 0000000..f792003 --- /dev/null +++ b/flash/util/Utils.as @@ -0,0 +1,389 @@ +package util +{ + import flash.display.*; + import flash.geom.*; + public class Utils + { + public static function GetChildren(clip:MovieClip):Array + { + var ret:Array = []; + for (var i = 0; i < clip.numChildren; i++) + { + ret.push(clip.getChildAt(i)); + } + return ret; + } + + /* + * angle difference + * (range -Math.PI to Math.PI) + */ + public static function GetAngleDiff(a, b) + { + var angleDiff = b - a; + + while (angleDiff > Math.PI) + { + angleDiff -= Math.PI * 2; + } + while (angleDiff < -Math.PI) + { + angleDiff += Math.PI * 2; + } + return angleDiff; + } + + /* + * angle difference + * (range 0 to Math.PI) + */ + public static function GetAngleDiffAbs(a, b) + { + var angleDiff = GetAngleDiff(a, b); + while (angleDiff < 0) + { + angleDiff += Math.PI * 2; + } + + if (angleDiff > Math.PI) + { + angleDiff = Math.PI * 2 - angleDiff; + } + + return angleDiff; + } + + public static function GetTransform(from:Matrix, to:Matrix) + { + var i:Matrix = from.clone(); + i.invert(); + var m:Matrix = to.clone(); + m.concat(i); + return m; + } + + public static function Decompose(m:Matrix) + { + var s:Point = ScaleFromMat(m); + m = m.clone(); + + var sxUnit = s.x >= 0 ? 1 : -1; + var syUnit = s.y >= 0 ? 1 : -1; + + m.scale(sxUnit, syUnit); + + //m.a /= sxUnit; + //m.d /= syUnit; + var rot = RotFromMat(m); + return {sx:s.x, sy:s.y, rot:rot}; + } + + public static function RotFromMat(m:Matrix) + { + return Math.atan2(-m.c, m.a); + } + + public static function ScaleFromMat(m:Matrix):Point + { + var xAxisX = m.a; + var xAxisY = m.c; + + var yAxisX = m.b; + var yAxisY = m.d; + + var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); + if (m.a < 0) sx *= -1; + + var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); + if (m.d < 0) sy *= -1; + + return new Point(sx, sy); + } + + public static function TransformRect(r:Rectangle, m:Matrix) + { + var p1:Point = new Point(r.left, r.top); + var p2:Point = new Point(r.right, r.top); + var p3:Point = new Point(r.left, r.bottom); + var p4:Point = new Point(r.right, r.bottom); + + p1 = m.transformPoint(p1); + p2 = m.transformPoint(p2); + p3 = m.transformPoint(p3); + p4 = m.transformPoint(p4); + + r.left = Math.min(p1.x, p2.x, p3.x, p4.x); + r.top = Math.min(p1.y, p2.y, p3.y, p4.y); + r.right = Math.max(p1.x, p2.x, p3.x, p4.x); + r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); + } + + public static function RoundRect(r:Rectangle) + { + r.left = Math.floor(r.left); + r.top = Math.floor(r.top); + r.right = Math.ceil(r.right); + r.bottom = Math.ceil(r.bottom); + } + + public static function ScaleRect(r:Rectangle, s) + { + r.left *= s; + r.top *= s; + r.right *= s; + r.bottom *= s; + } + + public static function RecursivelyStop(clip) + { + if (clip is MovieClip) + { + clip.stop(); + } + if (clip is DisplayObjectContainer) + { + for (var i = 0; i < clip.numChildren; i++) + { + RecursivelyStop(clip.getChildAt(i)); + } + } + } + + public static function WeirdGotoFrame(clip:MovieClip, frame) + { + var dir = clip.currentFrame > frame ? -1 : 1; + while (clip.currentFrame != frame) + { + RecurseDir(clip, dir); + } + } + + protected static function RecurseDir(clip:MovieClip, dir) + { + for (var i = 0; i < clip.numChildren; i++) + { + var child = clip.getChildAt(i); + if (child is MovieClip) + { + RecurseDir(child, dir); + } + } + if (dir == 1) + { + clip.nextFrame(); + } else { + clip.prevFrame(); + } + } + + protected static var tempSpace:BitmapData = null; + protected static var tempSpaceRect:Rectangle = new Rectangle(); + protected static var tempSpaceMatrix:Matrix = new Matrix(); + protected static var tempSpaceZero:Point = new Point(); + protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); + protected static var lastDrawOffset:Point = new Point(); + public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle + { + if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); + + var oldPad = 0; + var padAmount = 5; + + var ret:Rectangle = new Rectangle(); + + var baseBounds:Rectangle = clip.getBounds(clip); + + var boundsClip:DisplayObject = null; + if (clip is DisplayObjectContainer) + { + boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); + } + + if (boundsClip != null) + { + baseBounds = boundsClip.getBounds(clip); + } + + if (useMatrix) + { + TransformAABBRect(baseBounds, useMatrix); + } + + if (boundsClip != null) + { + return baseBounds; + } + + var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); + var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); + if (tempSpace == null) + { + tempSpace = new BitmapData(minW, minH, true, 0x0); + } + if (tempSpace.width < minW || tempSpace.height < minH) + { + tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); + } + + var r:Rectangle = new Rectangle(); + + baseBounds.left = Math.floor(baseBounds.left); + baseBounds.right = Math.ceil(baseBounds.right); + + baseBounds.top = Math.floor(baseBounds.top); + baseBounds.bottom = Math.ceil(baseBounds.bottom); + + var i; + + var needsChecking = true; + while (needsChecking) + { + needsChecking = false; + r.left = baseBounds.left - padAmount; + r.right = baseBounds.right + padAmount; + + r.top = baseBounds.top - padAmount; + r.bottom = baseBounds.bottom + padAmount; + + ret = r.clone(); + + tempSpaceRect.x = tempSpaceRect.y = 0; + tempSpaceRect.width = tempSpace.width; + tempSpaceRect.height = tempSpace.height; + tempSpace.fillRect(tempSpaceRect, 0x0); + + tempSpaceMatrix.identity(); + if (useMatrix) + { + tempSpaceMatrix.a = useMatrix.a; + tempSpaceMatrix.b = useMatrix.b; + tempSpaceMatrix.c = useMatrix.c; + tempSpaceMatrix.d = useMatrix.d; + tempSpaceMatrix.tx = useMatrix.tx; + tempSpaceMatrix.ty = useMatrix.ty; + } + tempSpaceMatrix.translate(-r.left, -r.top); + + lastDrawOffset.x = -r.left; + lastDrawOffset.y = -r.top; + tempSpace.draw(clip, tempSpaceMatrix); + + tempSpaceRect.width = 1; + tempSpaceRect.height = r.height; + + var sideMovedIn = 0; + for (i = 0; i < r.width; i++) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.left++; + sideMovedIn++; + } + } + if (ret.left < baseBounds.left - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.width - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.right--; + } + } + if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + sideMovedIn = 0; + tempSpaceRect.width = r.width; + tempSpaceRect.height = 1; + tempSpaceRect.x = 0; + for (i = 0; i < r.height; i++) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.top++; + sideMovedIn++; + } + } + if (ret.top < baseBounds.top - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.height - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.bottom--; + } + } + if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + } + return ret; + } + + public static function TransformAABBRect(r:Rectangle, m:Matrix) + { + var o1X = r.left; + var o1Y = r.top; + + var o2X = r.right; + var o2Y = r.top; + + var o3X = r.left; + var o3Y = r.bottom; + + var o4X = r.right; + var o4Y = r.bottom; + + var n1X = o1X * m.a + o1Y * m.c + m.tx; + var n1Y = o1X * m.b + o1Y * m.d + m.ty; + + var n2X = o2X * m.a + o2Y * m.c + m.tx; + var n2Y = o2X * m.b + o2Y * m.d + m.ty; + + var n3X = o3X * m.a + o3Y * m.c + m.tx; + var n3Y = o3X * m.b + o3Y * m.d + m.ty; + + var n4X = o4X * m.a + o4Y * m.c + m.tx; + var n4Y = o4X * m.b + o4Y * m.d + m.ty; + + r.left = Math.min(n1X, n2X, n3X, n4X); + r.right = Math.max(n1X, n2X, n3X, n4X); + + r.top = Math.min(n1Y, n2Y, n3Y, n4Y); + r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); + } + } +} diff --git a/job.py b/job.py index 989c991..77c09e8 100644 --- a/job.py +++ b/job.py @@ -3,6 +3,7 @@ import json from validate import * from args import * +import copy asset_src_schema = { "type":"object", @@ -69,19 +70,24 @@ base_path = os.path.join(self.out_dir, self.rel_path) if not os.path.exists(base_path): os.makedirs(base_path) + resource_names = [] for i,r in enumerate(resources): - path = os.path.join(base_path, "%s_%04d.png" % (self.name, i)) + resource_name = "%s_%04d.png" % (self.name, i) if len(resources) > 1 else self.name + ".png" + resource_names.append(resource_name) + path = os.path.join(base_path, resource_name) with open(path, "wb") as f: f.write(base64.b64decode(r)) if len(data) == 1: graphic_and_asset = {} (name, graphic_data) = data.items()[0] - graphic_and_asset = {"data":graphic_data} + graphic_and_asset = {"data":graphic_data, "resources":resource_names} with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps(graphic_and_asset)) else: + write_data = copy.deepcopy(data) + write_data["resources"] = resource_names with open(os.path.join(base_path, self.name + ".asset"), "w") as f: - f.write(pretty_dumps(data)) + f.write(pretty_dumps(write_data)) for name,details in data.iteritems(): with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps({"data":self.name + ".asset"})) diff --git a/old/Checkbox.as b/old/Checkbox.as deleted file mode 100644 index c5aaba2..0000000 --- a/old/Checkbox.as +++ /dev/null @@ -1,42 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - - public class Checkbox extends MovieClip - { - public var Enabled:Boolean = true; - public function Checkbox() - { - checkbox.gotoAndStop(1); - checkbox.addEventListener(MouseEvent.CLICK, Clicked); - } - - protected function Clicked(event) - { - if (!Enabled) return; - Toggle(); - if (OnClick != null) OnClick(OnClickParam); - } - - protected var checked = false; - public function set Checked(value) { checked = value; checkbox.gotoAndStop(checked ? 2 : 1); } - public function get Checked() { return checked; } - - public function set Text(value) { text.text = value; } - - public var OnClickParam; - public var OnClick; - - - public function Toggle() - { - checked = !checked; - checkbox.gotoAndStop(checked ? 2 : 1); - - - } - - } - -} diff --git a/old/GraphicExport-app.xml b/old/GraphicExport-app.xml deleted file mode 100644 index 5144634..0000000 --- a/old/GraphicExport-app.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - GraphicExport - 1.0 - GraphicExport - - GraphicExport - - - GraphicExport.swf - standard - false - true - false - portrait - auto - true - true - true - - - false - false - desktop extendedDesktop diff --git a/old/GraphicExport.exe b/old/GraphicExport.exe deleted file mode 100644 index 56315aa..0000000 --- a/old/GraphicExport.exe +++ /dev/null Binary files differ diff --git a/old/GraphicExport.fla b/old/GraphicExport.fla deleted file mode 100644 index 0b78ed7..0000000 --- a/old/GraphicExport.fla +++ /dev/null Binary files differ diff --git a/old/GraphicExport.swf b/old/GraphicExport.swf deleted file mode 100644 index 542db97..0000000 --- a/old/GraphicExport.swf +++ /dev/null Binary files differ diff --git a/old/NewGraphicDialog.as b/old/NewGraphicDialog.as deleted file mode 100644 index 152011c..0000000 --- a/old/NewGraphicDialog.as +++ /dev/null @@ -1,224 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - import flash.events.*; - import flash.filesystem.File; - import flash.net.FileFilter; - import Defs.GraphicDef; - import flash.text.engine.GraphicElement; - - public class NewGraphicDialog extends MovieClip - { - - public function NewGraphicDialog() - { - // constructor code - Init(); - } - - var typeButtons:Array = new Array(); - - public function Init() - { - graphicPath.text = "Path to Graphic Here"; - - this.removeChild(browseButton); - - var newBrowseButton = new UI_GenericBlueButton(); - newBrowseButton.Text = "Browse"; - newBrowseButton.OnClick = BrowseForFile; - newBrowseButton.x = browseButton.x + (newBrowseButton.width / 2); - newBrowseButton.y = browseButton.y + (newBrowseButton.height / 2); - addChild(newBrowseButton); - - var newTestButton = new UI_GenericBlueButton(); - newTestButton.Text = "Export"; - newTestButton.OnClick = TestFile; - newTestButton.x = testButton.x + (newTestButton.width / 2); - newTestButton.y = testButton.y + (newTestButton.height / 2); - addChild(newTestButton); - - this.removeChild(typePlaceholderButton); - - var typeX = typePlaceholderButton.x; - var typeY = typePlaceholderButton.y + (typePlaceholderButton.height / 2); - - - var typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Graphic (1)"; - typeButton.OnClick = function(){ SetType(1); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Skeletal (3)"; - typeButton.OnClick = function(){ SetType(3); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Scene (6)"; - typeButton.OnClick = function(){ SetType(6); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - animationCheckbox.Checked = true; - //browseButton - //typePlaceholderButton - //usesInput - //usesText.text = "" - } - - var usesInputDefaultText = "Comma Seperated List of Uses Here"; - - public static var fakeID = 9999999; - public function TestFile() - { - fakeID++; - var graphicName = graphicPath.text; - var graphicData = {id:fakeID,graphic:graphicPath.text,v:1,fs:0,p:0,type:selectedType}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new GraphicDef(graphicData); - - this.Hide(); - graphicExport.ExportItem(graphicDef); - } - - var selectedType = 1; - public function SetType(type:Number) - { - selectedType = type; - - for(var i = 0; i < typeButtons.length; i++) - { - typeButtons[i].Enabled = true; - } - - animationCheckbox.visible = false; - - switch(type) - { - case 1: { - typeButtons[0].Enabled = false; - animationCheckbox.visible = true; - break; - } - case 3: typeButtons[1].Enabled = false; break; - case 6: typeButtons[2].Enabled = false; break; - } - } - - var graphicExport:GraphicExport; - public function Show(parentClip) - { - this.graphicExport = parentClip; - - parentClip.addChild(this); - - SetType(selectedType); - - var graphicList = GameData.Instance().GraphicDefines; - - var usesString:String = ""; - var uniqueUseTypes:Array = new Array(); - for (var i = 0; i < graphicList.length; i++) - { - var graphicDef:GraphicDef = graphicList[i]; - var uses = graphicDef.ExportParams['uses']; - for (var usage in uses) - { - if (uniqueUseTypes[uses[usage]] == null) - { - uniqueUseTypes[uses[usage]] = uses[usage]; - usesString += uses[usage] + ", "; - } - } - } - - graphicPath.text = ""; - - } - - public function CloseClicked(event) - { - Hide(); - } - - public function Hide() - { - if (this.parent != null) this.parent.removeChild(this); - } - - public function BrowseForFile() - { - var file:File = new File(); - var swfTypeFilter:FileFilter = new FileFilter("SWF Files","*.swf"); - file.addEventListener(Event.SELECT, openFile); - file.browse([swfTypeFilter]); - } - - private function openFile(event:Event):void - { - _strace(event.target.nativePath); - var path:String = event.target.nativePath; - var pathParts:Array = path.split("Graphics\\"); - if (pathParts.length == 2) - { - var fileRemainder:String = pathParts[1]; - var withoutExtension:String = fileRemainder.split(".")[0]; - var pattern:RegExp = /\\/g; - withoutExtension = withoutExtension.replace(pattern, "/"); - _strace(withoutExtension); - graphicPath.text = withoutExtension; - - if (withoutExtension.indexOf("Backgrounds") > -1) - { - SetType(6); - } - - if (withoutExtension.indexOf("Monsters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Characters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Portraits") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Quest") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Equipment") > -1) - { - SetType(1); - } - - - } - } - - - } - -} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/flash/util/RectangleNode.as b/flash/util/RectangleNode.as new file mode 100644 index 0000000..6f31e44 --- /dev/null +++ b/flash/util/RectangleNode.as @@ -0,0 +1,178 @@ +package util { + import flash.geom.Rectangle; + + public class RectangleNode + { + public var Left:RectangleNode = null; + public var Right:RectangleNode = null; + public var Rect:Rectangle = null; + public var InUse:Boolean = false; + public var Removed:Boolean = false; + public var Parent:RectangleNode = null; + public var AllocationID = 0; + public var Host:RectanglePacker= null; + public var MinAllocationID = 0; + public var NodeID; + public static var NextNodeID = 0; + + public var DontRemove = false; + + public var LastAccessTime = 0; + + public var Flags = []; + + public var UpdateTo:RectangleNode = null; + + /* + public function get Removed() + { + return _Removed; + } + + public function set Removed(r) + { + this._Removed = r; + } + + public function get Host():RectanglePacker + { + return _Host; + } + public function set Host(p:RectanglePacker) + { + this._Host = p; + + if (_Left && _Left.Host != p) + { + throw new Error("bad left host"); + } + if (_Right && _Right.Host != p) + { + throw new Error("bad right host"); + } + if (_Parent && _Parent.Host != p) + { + throw new Error("bad parent host"); + } + + } + + public function get Left():RectangleNode + { + return _Left; + } + public function set Left(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad left host"); + } + _Left = n; + } + public function get Right():RectangleNode + { + return _Right; + } + public function set Right(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad right host"); + } + _Right = n; + } + + public function get Parent():RectangleNode + { + return _Parent; + } + public function set Parent(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad parent host"); + } + _Parent = n; + } + */ + public function get IsFreeSpace() + { + return Left == null && Right == null && !InUse; + } + public function UpdateLinksFromNode(node:RectangleNode) + { + if (node.Parent) + { + if (node.Parent.Left == node) + { + node.Parent.Left = this; + } + if (node.Parent.Right == node) + { + node.Parent.Right = this; + } + } + if (node.Left) + { + node.Left.Parent = this; + } + if (node.Right) + { + node.Right.Parent = this; + } + } + public function MakeFromNode(node:RectangleNode) + { + //_Host = node.Host; + Host = node.Host; + Left = node.Left; + Right = node.Right; + Parent = node.Parent; + AllocationID = node.AllocationID; + InUse = node.InUse; + MinAllocationID = node.MinAllocationID; + NodeID = node.NodeID; + Rect = node.Rect.clone(); + Removed = node.Removed; + DontRemove = node.DontRemove; + } + public function RectangleNode(x, y, w, h, host:RectanglePacker) + { + this.NodeID = NextNodeID++; + this.Host = host; + this.Rect = new Rectangle(x, y, w, h); + } + public function OutputJSON() + { + var node = {}; + node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; + node.in_use = InUse; + node.id = NodeID; + if (this.Left) node.left = this.Left.OutputJSON(); + if (this.Right) node.right = this.Right.OutputJSON(); + return node; + } + + public function ReadJSON(details) + { + details.new_node = this; + this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); + this.Removed = false; + + this.InUse = details.in_use; + + if (details.hasOwnProperty("right")) + { + this.Right = new RectangleNode(0, 0, 0, 0, this.Host); + Right.ReadJSON(details.right); + Right.Parent = this; + } + if (details.hasOwnProperty("left")) + { + this.Left = new RectangleNode(0, 0, 0, 0, this.Host); + Left.ReadJSON(details.left); + Left.Parent = this; + } + } + } +} diff --git a/flash/util/RectanglePacker.as b/flash/util/RectanglePacker.as new file mode 100644 index 0000000..597d7fd --- /dev/null +++ b/flash/util/RectanglePacker.as @@ -0,0 +1,562 @@ +package util { + import flash.geom.*; + import flash.display.BitmapData; + import flash.display.MovieClip; + import flash.text.TextField; + import flash.events.*; + import flash.sampler.StackFrame; + + public class RectanglePacker + { + protected var w:int; + protected var h:int; + protected var root:RectangleNode; + public var NextAllocationID = 0; + + public function get width():int { return w; } + public function get height():int { return h; } + + public function RectanglePacker(w, h) + { + this.w = w; + this.h = h; + root = new RectangleNode(0, 0, w, h, this); + root.AllocationID = -1; + } + protected var area = 0; + + protected var testRender:MovieClip = new MovieClip(); + + public function GetRoot():RectangleNode + { + return root; + } + + public function GetLeafNodes():Array + { + return GetLeafNodesInternal(root); + } + + protected function GetLeafNodesInternal(n:RectangleNode):Array + { + if (n.InUse) return [n]; + var ret:Array = new Array(); + if (n.Left) ret = GetLeafNodesInternal(n.Left); + if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); + return ret; + } + + public function GetUsedArea() + { + return area; + } + + public function get efficiency() + { + return area / (w * h); + } + + protected function RectCost(w, h) + { + if (w == 0 || h == 0) return 99999999; + return (Math.max(w, h) / Math.min(w, h)) * w * h; + } + + protected function EnumerateTree(r:RectangleNode = null, indent = "") + { + if (r == null) r = this.root; + var str = ""; + str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; + if (r.Left) str += EnumerateTree(r.Left, indent + " "); + if (r.Right) str += EnumerateTree(r.Left, indent + " "); + return str; + } + + /* + * Remove a list of nodes from the tree. + * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree + * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, + leaving the original objects intact (in case something still references them) + */ + public function RemoveNodes(nodes:Array, fullyDestroy = true) + { + + /* DEBUG CHECKS */ + /* + this.PerformDebugCheck(); + + var str = ""; + for (var i = 0; i < nodes.length; i++) + { + str += nodes[i].NodeID + "\n"; + } + + var orig = nodes.concat(); + + var strs = [str, EnumerateTree()]; + + RenderDetailsBox.StartTrack("PackRemoveTime"); + + for (var i = 0; i < nodes.length; i++) + { + var n:RectangleNode = nodes[i]; + if (n.Host != this) + { + throw new Error("bad host!"); + } + } + */ + /* END DEBUG CHECKS */ + + var i, n:RectangleNode, p:RectangleNode; + + // setup the Removed flag on every node that should be removed + // we also check at this time to see if any more nodes need to be removed, such as a parent of + // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + if (n.Host == this) + { + n.Removed = true; + + if (n.InUse) + { + // sum up the total removed area + area -= n.Rect.width * n.Rect.height; + } + + if (n.Parent != null) + { + p = n.Parent; + // check and see if the current node's parent still has any valid children + if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) + { + // all of the current nodes siblings are either being removed or are blank, so + // we can remove the parent too + if (p.Left.IsFreeSpace) + { + // the left child was empty space before, so we can remove it (if it wasn't + // empty space it is already being removed so it doesn't need to be added + // to the list) + if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); + } + if (p.Right.IsFreeSpace) + { + // the right child was empty space before, so we can remove it + if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); + } + if (p != root && nodes.indexOf(p) == -1) + { + // remove the parent node too (provided it isn't the root!) + nodes.push(p); + } + } + } + } + } + + // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, + // so go ahead and remove them + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + + if (n.Parent != null) + { + // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not + // also getting removed!) + p = n.Parent; + + if (!p.Removed) + { + if (p.Left && p.Right) + { + var newNode:RectangleNode; + if (p.Left.Removed && p.Right.Removed) + { + // both children were removed, but the parent wasn't, so the parent must be root + // (since we never remove the root) + if (p != root) + { + throw new Error("should be root"); + } + p.Left.Parent = null; + p.Right.Parent = null; + p.Left = null; + p.Right = null; + p.InUse = false; + } else if (!p.Left.Removed) { + // Right node removed, Left node not removed + if (!p.Left.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Right); + newNode.UpdateLinksFromNode(p.Right); + } + // Left node is used + p.Right.InUse = false; + p.Right.Left = null; + p.Right.Right = null; + p.Right.Removed = false; + } else { + throw new Error("should have been caught above!"); + } + } else { + // Left node removed, Right node not removed + if (!p.Right.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Left); + newNode.UpdateLinksFromNode(p.Left); + } + // Left node is used + //p.Left.Removed = true; + p.Left.InUse = false; + p.Left.Left = null; + p.Left.Right = null; + p.Left.Removed = false; + //p.Left.Parent = null; + } else { + throw new Error("should have been caught above!"); + } + } + } else { + // huh? how does n.Parent == p but p has no children? something went wrong + throw new Error("shouldn't have gotten here"); + } + } + } + //strs.push(EnumerateTree()); + } + } + + public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode + { + + var node:RectangleNode = FindSizedNode(w, h, root); + + if (node == null) + { + //UHOH, texture full + return null; + } + area += w * h; + node.InUse = true; + + var splitVertFirstCost = 0; + if (w < node.Rect.width) + { + splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); + } + + var splitHorizFirstCost = 0; + if (h < node.Rect.height) + { + splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); + } + + + + if (splitVertFirstCost <= splitHorizFirstCost) + { + node.Flags.push("SplitVertFirst"); + if (w < node.Rect.width) + { + node.Flags.push("SplitVert"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + if (h < node.Rect.height) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + } else { + node.Flags.push("SplitHorzFirst"); + if (h < node.Rect.height) + { + node.Flags.push("SplitVert"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + if (w < node.Rect.width) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + } + NextAllocationID++; + if (useInstead) + { + useInstead.MakeFromNode(node); + useInstead.UpdateLinksFromNode(node); + useInstead.Flags = node.Flags; + node = useInstead; + node.Flags.push("UseInstead"); + } + + //if (!CheckOKNode(node)) node.Flags.push("BadNode"); + + return node; + } + public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) + { + if (r == null) r = this.root; + if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) + { + var ancestor:RectangleNode = FindCommonNode(n, r); + throw new Error("bad node allocated!"); + return false; + } + var ok = true; + if (r.Left) ok = ok && CheckOKNode(n, r.Left); + if (r.Right) ok = ok && CheckOKNode(n, r.Right); + return ok; + } + + public function PerformDebugCheck() + { + DebugInternal(this.root); + } + + protected function DebugInternal(n:RectangleNode) + { + if (n.Host != this) + { + throw new Error("problem with host!"); + } + if (n.IsFreeSpace) + { + if (n.Left || n.Right) + { + throw new Error("shouldn't have children"); + } + } + if ((n.Left && !n.Right) || (n.Right && !n.Left)) + { + throw new Error("mismatched children"); + } + if (n.Left && n.Left.Parent != n) + { + throw new Error("left child has bad parent"); + } + if (n.Right && n.Right.Parent != n) + { + throw new Error("right child has bad parent"); + } + if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) + { + throw new Error("problem with parent"); + } + if (n.Left) DebugInternal(n.Left); + if (n.Right) DebugInternal(n.Right); + } + + public function FindCommonNode(a:RectangleNode, b:RectangleNode) + { + var aHistory = []; + var bHistory = []; + while (a != null) + { + aHistory.push(a); + a = a.Parent; + } + while (b != null) + { + bHistory.push(b); + b = b.Parent; + } + var i = aHistory.length - 1; + var j = bHistory.length - 1; + var same = null; + while (i >= 0 && j >= 0) + { + if (aHistory[i] == bHistory[j]) + { + same = aHistory[i]; + } else { + break; + } + i--; + j--; + } + return same; + } + + public function TestRender() + { + while (testRender.numChildren > 0) + { + testRender.removeChildAt(0); + } + testRender.graphics.clear(); + TestRenderNode(root, testRender); + return testRender; + } + protected function TestRenderNode(n:RectangleNode, m:MovieClip) + { + var g:MovieClip = new MovieClip(); + m.addChild(g); + g.graphics.lineStyle(1, 0, 1); + if (n.Left != null) TestRenderNode(n.Left, m); + if (n.Left != null) TestRenderNode(n.Right, m); + if (n.InUse) + { + g.graphics.beginFill(0xFFFF00, 0.2); + } + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + if (n.InUse) + { + g.graphics.endFill(); + var t:TextField = new TextField(); + t.text = n.NodeID; + t.x = n.Rect.x + n.Rect.width / 2.0; + t.y = n.Rect.y + n.Rect.height / 2.0; + g.addChild(t); + g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); + g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); + } + + } + public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) + { + if (n.InUse) + { + //_trace(Math.round(n.LastAccessTime / 1000)); + } + var p:RectangleNode = n.Parent; + if (p) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); + g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); + g.graphics.endFill(); + t.text = p.NodeID; + if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); + g.oldListener = function(e){MouseOver(p, g, t);}; + g.addEventListener(MouseEvent.CLICK, g.oldListener); + } + } + public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(0xFFFF00, 0.2); + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + g.graphics.endFill(); + t.text = n.NodeID; + } + protected function SplitVert(node:RectangleNode, leftWidth) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function SplitHoriz(node:RectangleNode, topHeight) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode + { + if (node.InUse) return null; + if (node.Rect.width >= w && node.Rect.height >= h) + { + if (node.Left != null && node.Right != null) + { + var t:RectangleNode = FindSizedNode(w, h, node.Left); + if (t != null) return t; + t = FindSizedNode(w, h, node.Right); + return t; + } else { + return node; + } + } + return null; + } + + public function LoadTree(details) + { + this.root = new RectangleNode(0, 0, 0, 0, this); + root.ReadJSON(details); + + this.NextAllocationID = 0; + this.area = 0; + + var queue:Array = new Array(); + queue.push(root); + while (queue.length > 0) + { + var node:RectangleNode = queue.shift(); + node.AllocationID = NextAllocationID; + node.MinAllocationID = NextAllocationID; + if (node.Left) queue.push(node.Left); + if (node.Right) queue.push(node.Right); + if (node.InUse) this.area += node.Rect.width * node.Rect.height; + } + NextAllocationID++; + } + + public function GetNodePath(node:RectangleNode) + { + var output:String = ""; + while (node != this.root) + { + output = (node == node.Parent.Left ? "l" : "r") + output; + node = node.Parent; + } + return output; + } + + public function GetNodeFromPath(path:String):RectangleNode + { + var node:RectangleNode = this.root; + for (var i = 0; i < path.length; i++) + { + if (!node) return null; + if (path.charAt(i) == "r") + { + node = node.Right; + } else { + node = node.Left; + } + } + return node; + } + } +} diff --git a/flash/util/Utils.as b/flash/util/Utils.as new file mode 100644 index 0000000..f792003 --- /dev/null +++ b/flash/util/Utils.as @@ -0,0 +1,389 @@ +package util +{ + import flash.display.*; + import flash.geom.*; + public class Utils + { + public static function GetChildren(clip:MovieClip):Array + { + var ret:Array = []; + for (var i = 0; i < clip.numChildren; i++) + { + ret.push(clip.getChildAt(i)); + } + return ret; + } + + /* + * angle difference + * (range -Math.PI to Math.PI) + */ + public static function GetAngleDiff(a, b) + { + var angleDiff = b - a; + + while (angleDiff > Math.PI) + { + angleDiff -= Math.PI * 2; + } + while (angleDiff < -Math.PI) + { + angleDiff += Math.PI * 2; + } + return angleDiff; + } + + /* + * angle difference + * (range 0 to Math.PI) + */ + public static function GetAngleDiffAbs(a, b) + { + var angleDiff = GetAngleDiff(a, b); + while (angleDiff < 0) + { + angleDiff += Math.PI * 2; + } + + if (angleDiff > Math.PI) + { + angleDiff = Math.PI * 2 - angleDiff; + } + + return angleDiff; + } + + public static function GetTransform(from:Matrix, to:Matrix) + { + var i:Matrix = from.clone(); + i.invert(); + var m:Matrix = to.clone(); + m.concat(i); + return m; + } + + public static function Decompose(m:Matrix) + { + var s:Point = ScaleFromMat(m); + m = m.clone(); + + var sxUnit = s.x >= 0 ? 1 : -1; + var syUnit = s.y >= 0 ? 1 : -1; + + m.scale(sxUnit, syUnit); + + //m.a /= sxUnit; + //m.d /= syUnit; + var rot = RotFromMat(m); + return {sx:s.x, sy:s.y, rot:rot}; + } + + public static function RotFromMat(m:Matrix) + { + return Math.atan2(-m.c, m.a); + } + + public static function ScaleFromMat(m:Matrix):Point + { + var xAxisX = m.a; + var xAxisY = m.c; + + var yAxisX = m.b; + var yAxisY = m.d; + + var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); + if (m.a < 0) sx *= -1; + + var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); + if (m.d < 0) sy *= -1; + + return new Point(sx, sy); + } + + public static function TransformRect(r:Rectangle, m:Matrix) + { + var p1:Point = new Point(r.left, r.top); + var p2:Point = new Point(r.right, r.top); + var p3:Point = new Point(r.left, r.bottom); + var p4:Point = new Point(r.right, r.bottom); + + p1 = m.transformPoint(p1); + p2 = m.transformPoint(p2); + p3 = m.transformPoint(p3); + p4 = m.transformPoint(p4); + + r.left = Math.min(p1.x, p2.x, p3.x, p4.x); + r.top = Math.min(p1.y, p2.y, p3.y, p4.y); + r.right = Math.max(p1.x, p2.x, p3.x, p4.x); + r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); + } + + public static function RoundRect(r:Rectangle) + { + r.left = Math.floor(r.left); + r.top = Math.floor(r.top); + r.right = Math.ceil(r.right); + r.bottom = Math.ceil(r.bottom); + } + + public static function ScaleRect(r:Rectangle, s) + { + r.left *= s; + r.top *= s; + r.right *= s; + r.bottom *= s; + } + + public static function RecursivelyStop(clip) + { + if (clip is MovieClip) + { + clip.stop(); + } + if (clip is DisplayObjectContainer) + { + for (var i = 0; i < clip.numChildren; i++) + { + RecursivelyStop(clip.getChildAt(i)); + } + } + } + + public static function WeirdGotoFrame(clip:MovieClip, frame) + { + var dir = clip.currentFrame > frame ? -1 : 1; + while (clip.currentFrame != frame) + { + RecurseDir(clip, dir); + } + } + + protected static function RecurseDir(clip:MovieClip, dir) + { + for (var i = 0; i < clip.numChildren; i++) + { + var child = clip.getChildAt(i); + if (child is MovieClip) + { + RecurseDir(child, dir); + } + } + if (dir == 1) + { + clip.nextFrame(); + } else { + clip.prevFrame(); + } + } + + protected static var tempSpace:BitmapData = null; + protected static var tempSpaceRect:Rectangle = new Rectangle(); + protected static var tempSpaceMatrix:Matrix = new Matrix(); + protected static var tempSpaceZero:Point = new Point(); + protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); + protected static var lastDrawOffset:Point = new Point(); + public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle + { + if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); + + var oldPad = 0; + var padAmount = 5; + + var ret:Rectangle = new Rectangle(); + + var baseBounds:Rectangle = clip.getBounds(clip); + + var boundsClip:DisplayObject = null; + if (clip is DisplayObjectContainer) + { + boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); + } + + if (boundsClip != null) + { + baseBounds = boundsClip.getBounds(clip); + } + + if (useMatrix) + { + TransformAABBRect(baseBounds, useMatrix); + } + + if (boundsClip != null) + { + return baseBounds; + } + + var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); + var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); + if (tempSpace == null) + { + tempSpace = new BitmapData(minW, minH, true, 0x0); + } + if (tempSpace.width < minW || tempSpace.height < minH) + { + tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); + } + + var r:Rectangle = new Rectangle(); + + baseBounds.left = Math.floor(baseBounds.left); + baseBounds.right = Math.ceil(baseBounds.right); + + baseBounds.top = Math.floor(baseBounds.top); + baseBounds.bottom = Math.ceil(baseBounds.bottom); + + var i; + + var needsChecking = true; + while (needsChecking) + { + needsChecking = false; + r.left = baseBounds.left - padAmount; + r.right = baseBounds.right + padAmount; + + r.top = baseBounds.top - padAmount; + r.bottom = baseBounds.bottom + padAmount; + + ret = r.clone(); + + tempSpaceRect.x = tempSpaceRect.y = 0; + tempSpaceRect.width = tempSpace.width; + tempSpaceRect.height = tempSpace.height; + tempSpace.fillRect(tempSpaceRect, 0x0); + + tempSpaceMatrix.identity(); + if (useMatrix) + { + tempSpaceMatrix.a = useMatrix.a; + tempSpaceMatrix.b = useMatrix.b; + tempSpaceMatrix.c = useMatrix.c; + tempSpaceMatrix.d = useMatrix.d; + tempSpaceMatrix.tx = useMatrix.tx; + tempSpaceMatrix.ty = useMatrix.ty; + } + tempSpaceMatrix.translate(-r.left, -r.top); + + lastDrawOffset.x = -r.left; + lastDrawOffset.y = -r.top; + tempSpace.draw(clip, tempSpaceMatrix); + + tempSpaceRect.width = 1; + tempSpaceRect.height = r.height; + + var sideMovedIn = 0; + for (i = 0; i < r.width; i++) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.left++; + sideMovedIn++; + } + } + if (ret.left < baseBounds.left - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.width - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.right--; + } + } + if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + sideMovedIn = 0; + tempSpaceRect.width = r.width; + tempSpaceRect.height = 1; + tempSpaceRect.x = 0; + for (i = 0; i < r.height; i++) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.top++; + sideMovedIn++; + } + } + if (ret.top < baseBounds.top - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.height - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.bottom--; + } + } + if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + } + return ret; + } + + public static function TransformAABBRect(r:Rectangle, m:Matrix) + { + var o1X = r.left; + var o1Y = r.top; + + var o2X = r.right; + var o2Y = r.top; + + var o3X = r.left; + var o3Y = r.bottom; + + var o4X = r.right; + var o4Y = r.bottom; + + var n1X = o1X * m.a + o1Y * m.c + m.tx; + var n1Y = o1X * m.b + o1Y * m.d + m.ty; + + var n2X = o2X * m.a + o2Y * m.c + m.tx; + var n2Y = o2X * m.b + o2Y * m.d + m.ty; + + var n3X = o3X * m.a + o3Y * m.c + m.tx; + var n3Y = o3X * m.b + o3Y * m.d + m.ty; + + var n4X = o4X * m.a + o4Y * m.c + m.tx; + var n4Y = o4X * m.b + o4Y * m.d + m.ty; + + r.left = Math.min(n1X, n2X, n3X, n4X); + r.right = Math.max(n1X, n2X, n3X, n4X); + + r.top = Math.min(n1Y, n2Y, n3Y, n4Y); + r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); + } + } +} diff --git a/job.py b/job.py index 989c991..77c09e8 100644 --- a/job.py +++ b/job.py @@ -3,6 +3,7 @@ import json from validate import * from args import * +import copy asset_src_schema = { "type":"object", @@ -69,19 +70,24 @@ base_path = os.path.join(self.out_dir, self.rel_path) if not os.path.exists(base_path): os.makedirs(base_path) + resource_names = [] for i,r in enumerate(resources): - path = os.path.join(base_path, "%s_%04d.png" % (self.name, i)) + resource_name = "%s_%04d.png" % (self.name, i) if len(resources) > 1 else self.name + ".png" + resource_names.append(resource_name) + path = os.path.join(base_path, resource_name) with open(path, "wb") as f: f.write(base64.b64decode(r)) if len(data) == 1: graphic_and_asset = {} (name, graphic_data) = data.items()[0] - graphic_and_asset = {"data":graphic_data} + graphic_and_asset = {"data":graphic_data, "resources":resource_names} with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps(graphic_and_asset)) else: + write_data = copy.deepcopy(data) + write_data["resources"] = resource_names with open(os.path.join(base_path, self.name + ".asset"), "w") as f: - f.write(pretty_dumps(data)) + f.write(pretty_dumps(write_data)) for name,details in data.iteritems(): with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps({"data":self.name + ".asset"})) diff --git a/old/Checkbox.as b/old/Checkbox.as deleted file mode 100644 index c5aaba2..0000000 --- a/old/Checkbox.as +++ /dev/null @@ -1,42 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - - public class Checkbox extends MovieClip - { - public var Enabled:Boolean = true; - public function Checkbox() - { - checkbox.gotoAndStop(1); - checkbox.addEventListener(MouseEvent.CLICK, Clicked); - } - - protected function Clicked(event) - { - if (!Enabled) return; - Toggle(); - if (OnClick != null) OnClick(OnClickParam); - } - - protected var checked = false; - public function set Checked(value) { checked = value; checkbox.gotoAndStop(checked ? 2 : 1); } - public function get Checked() { return checked; } - - public function set Text(value) { text.text = value; } - - public var OnClickParam; - public var OnClick; - - - public function Toggle() - { - checked = !checked; - checkbox.gotoAndStop(checked ? 2 : 1); - - - } - - } - -} diff --git a/old/GraphicExport-app.xml b/old/GraphicExport-app.xml deleted file mode 100644 index 5144634..0000000 --- a/old/GraphicExport-app.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - GraphicExport - 1.0 - GraphicExport - - GraphicExport - - - GraphicExport.swf - standard - false - true - false - portrait - auto - true - true - true - - - false - false - desktop extendedDesktop diff --git a/old/GraphicExport.exe b/old/GraphicExport.exe deleted file mode 100644 index 56315aa..0000000 --- a/old/GraphicExport.exe +++ /dev/null Binary files differ diff --git a/old/GraphicExport.fla b/old/GraphicExport.fla deleted file mode 100644 index 0b78ed7..0000000 --- a/old/GraphicExport.fla +++ /dev/null Binary files differ diff --git a/old/GraphicExport.swf b/old/GraphicExport.swf deleted file mode 100644 index 542db97..0000000 --- a/old/GraphicExport.swf +++ /dev/null Binary files differ diff --git a/old/NewGraphicDialog.as b/old/NewGraphicDialog.as deleted file mode 100644 index 152011c..0000000 --- a/old/NewGraphicDialog.as +++ /dev/null @@ -1,224 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - import flash.events.*; - import flash.filesystem.File; - import flash.net.FileFilter; - import Defs.GraphicDef; - import flash.text.engine.GraphicElement; - - public class NewGraphicDialog extends MovieClip - { - - public function NewGraphicDialog() - { - // constructor code - Init(); - } - - var typeButtons:Array = new Array(); - - public function Init() - { - graphicPath.text = "Path to Graphic Here"; - - this.removeChild(browseButton); - - var newBrowseButton = new UI_GenericBlueButton(); - newBrowseButton.Text = "Browse"; - newBrowseButton.OnClick = BrowseForFile; - newBrowseButton.x = browseButton.x + (newBrowseButton.width / 2); - newBrowseButton.y = browseButton.y + (newBrowseButton.height / 2); - addChild(newBrowseButton); - - var newTestButton = new UI_GenericBlueButton(); - newTestButton.Text = "Export"; - newTestButton.OnClick = TestFile; - newTestButton.x = testButton.x + (newTestButton.width / 2); - newTestButton.y = testButton.y + (newTestButton.height / 2); - addChild(newTestButton); - - this.removeChild(typePlaceholderButton); - - var typeX = typePlaceholderButton.x; - var typeY = typePlaceholderButton.y + (typePlaceholderButton.height / 2); - - - var typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Graphic (1)"; - typeButton.OnClick = function(){ SetType(1); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Skeletal (3)"; - typeButton.OnClick = function(){ SetType(3); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Scene (6)"; - typeButton.OnClick = function(){ SetType(6); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - animationCheckbox.Checked = true; - //browseButton - //typePlaceholderButton - //usesInput - //usesText.text = "" - } - - var usesInputDefaultText = "Comma Seperated List of Uses Here"; - - public static var fakeID = 9999999; - public function TestFile() - { - fakeID++; - var graphicName = graphicPath.text; - var graphicData = {id:fakeID,graphic:graphicPath.text,v:1,fs:0,p:0,type:selectedType}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new GraphicDef(graphicData); - - this.Hide(); - graphicExport.ExportItem(graphicDef); - } - - var selectedType = 1; - public function SetType(type:Number) - { - selectedType = type; - - for(var i = 0; i < typeButtons.length; i++) - { - typeButtons[i].Enabled = true; - } - - animationCheckbox.visible = false; - - switch(type) - { - case 1: { - typeButtons[0].Enabled = false; - animationCheckbox.visible = true; - break; - } - case 3: typeButtons[1].Enabled = false; break; - case 6: typeButtons[2].Enabled = false; break; - } - } - - var graphicExport:GraphicExport; - public function Show(parentClip) - { - this.graphicExport = parentClip; - - parentClip.addChild(this); - - SetType(selectedType); - - var graphicList = GameData.Instance().GraphicDefines; - - var usesString:String = ""; - var uniqueUseTypes:Array = new Array(); - for (var i = 0; i < graphicList.length; i++) - { - var graphicDef:GraphicDef = graphicList[i]; - var uses = graphicDef.ExportParams['uses']; - for (var usage in uses) - { - if (uniqueUseTypes[uses[usage]] == null) - { - uniqueUseTypes[uses[usage]] = uses[usage]; - usesString += uses[usage] + ", "; - } - } - } - - graphicPath.text = ""; - - } - - public function CloseClicked(event) - { - Hide(); - } - - public function Hide() - { - if (this.parent != null) this.parent.removeChild(this); - } - - public function BrowseForFile() - { - var file:File = new File(); - var swfTypeFilter:FileFilter = new FileFilter("SWF Files","*.swf"); - file.addEventListener(Event.SELECT, openFile); - file.browse([swfTypeFilter]); - } - - private function openFile(event:Event):void - { - _strace(event.target.nativePath); - var path:String = event.target.nativePath; - var pathParts:Array = path.split("Graphics\\"); - if (pathParts.length == 2) - { - var fileRemainder:String = pathParts[1]; - var withoutExtension:String = fileRemainder.split(".")[0]; - var pattern:RegExp = /\\/g; - withoutExtension = withoutExtension.replace(pattern, "/"); - _strace(withoutExtension); - graphicPath.text = withoutExtension; - - if (withoutExtension.indexOf("Backgrounds") > -1) - { - SetType(6); - } - - if (withoutExtension.indexOf("Monsters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Characters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Portraits") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Quest") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Equipment") > -1) - { - SetType(1); - } - - - } - } - - - } - -} diff --git a/old/PNGExportHelper.as b/old/PNGExportHelper.as deleted file mode 100644 index f8c4c9d..0000000 --- a/old/PNGExportHelper.as +++ /dev/null @@ -1,253 +0,0 @@ -package -{ - import flash.display.*; - import com.adobe.images.*; - import flash.utils.*; - import flash.net.*; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import flash.geom.Point; - - public class PNGExportHelper - { - public static var UseExpandedBitmaps = false; - public static var AlphaThreshold = 5; - - private static function ExpandBitmapBorders(bd:BitmapData, bgColor = 0x0, passes = 1):BitmapData - { - /* - var thresh:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - thresh.threshold(bd, bd.rect, new Point(), "<", (20 << 24), bgColor, 0xFF000000, true); - */ - var sampled:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - bd.lock(); - sampled.lock(); - - for (var y = 0; y < bd.height; y++) - { - for (var x = 0; x < bd.width; x++) - { - var oldVal:uint = bd.getPixel32(x, y); - var a:uint = (oldVal & 0xFF000000) >>> 24; - var rgb:uint = (oldVal & 0xFFFFFF); - if (a > AlphaThreshold) - { - sampled.setPixel32(x, y, (0xFF << 24) | rgb); - } - else - { - sampled.setPixel32(x, y, bgColor); - } - } - } - sampled.unlock(); - bd.unlock(); - - return ExpandBitmapBordersInternal(sampled, bgColor, passes); - } - - private static function ExpandBitmapBordersInternal(bd:BitmapData, bgColor, passes):BitmapData - { - var output:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - - var scale = 16; - var scaled:BitmapData = new BitmapData(bd.width/scale, bd.height/scale, true, bgColor); - var mat:Matrix = new Matrix(); - mat.scale(1/scale, 1/scale); - scaled.draw(bd, mat, null, null, null, true); - - output.lock(); - - var colors:Array = new Array(); - var weights:Array = new Array(); - - for (var oy = 0; oy < scaled.height; oy++) - { - - for (var ox = 0; ox < scaled.width; ox++) - { - - var scaledVal:uint = scaled.getPixel32(ox, oy); - var scaleda:uint = (scaledVal & 0xFF000000) >>> 24; - if (scaleda == 0 || scaleda == 255) - { - output.copyPixels(bd, new Rectangle(ox * scale, oy * scale, scale, scale), new Point(ox * scale, oy * scale)); - continue; - } else { - //_strace(scaleda+""); - } - - - for (var y = oy * scale; y < oy * scale + scale; y++) - { - for (var x = ox * scale; x < ox * scale + scale; x++) - { - var oldVal:uint = bd.getPixel32(x, y); - var a:uint = (oldVal & 0xFF000000) >>> 24; - var rgb:uint = (oldVal & 0xFFFFFF); - - if (a == 0 && rgb == bgColor) - { - colors.length = 0; - weights.length = 0; - - for (var y1 = y - 2; y1 <= y + 2; y1++) - { - for (var x1 = x - 2; x1 <= x + 2; x1++) - { - var dist = Math.abs(x1 - x) + Math.abs(y1 - y); - if (dist >= 3) continue; - - if (x1 >= 0 && x1 < bd.width && y1 >= 0 && y1 < bd.height) - { - colors.push(bd.getPixel(x1, y1)); - weights.push(1 - dist * 0.2); - } - } - } - - var newVal = AveragePixels(colors, weights, bgColor); - if (newVal == null) - { - newVal = oldVal; - } - else - { - var newR:uint = (newVal & 0xFF0000) >> 16; - var newG:uint = (newVal & 0xFF00) >> 8; - var newB:uint = (newVal & 0xFF); - - if (newVal != 0 && colors.length >= 4) - { - var bp = true; - } - - var sorted = colors.sort(function(a, b) - { - var aR:uint = (a & 0xFF0000) >> 16; - var aG:uint = (a & 0xFF00) >> 8; - var aB:uint = (a & 0xFF); - - var bR:uint = (b & 0xFF0000) >> 16; - var bG:uint = (b & 0xFF00) >> 8; - var bB:uint = (b & 0xFF); - - var diffA = Math.abs(aR - newR) + Math.abs(aG - newG) + Math.abs(aB - newB); - var diffB = Math.abs(bR - newR) + Math.abs(bG - newG) + Math.abs(bB - newB); - - return diffA - diffB; - - }, Array.RETURNINDEXEDARRAY | Array.DESCENDING); - - var toRemove = Math.min(2, colors.length - 4); - var removed = 0; - for (var i = 0; i < colors.length; i++) - { - var index = sorted.indexOf(i + removed); - if (index < toRemove) - { - colors.splice(i, 1); - weights.splice(i, 1); - removed++; - i--; - if (removed == toRemove) break; - } - } - - var fixOutliersVal = AveragePixels(colors, weights, bgColor); - if (fixOutliersVal == null) newVal = (0xFF << 24) | newVal; - - newVal = (0xFF << 24) | fixOutliersVal; - } - - output.setPixel32(x, y, newVal); - } - else - { - output.setPixel32(x, y, oldVal); - } - } - } - }//end outer scaled x - }//End outer scaled y - - bd.unlock(); - output.unlock(); - - passes--; - if (passes > 0) - { - return ExpandBitmapBordersInternal(output, bgColor, passes); - } - else - { - return output; - } - } - - private static function AveragePixels(colors:Array, weights:Array, bgColor:uint):uint - { - var rTotal = 0; - var gTotal = 0; - var bTotal = 0; - - var wTotal = 0; - - for (var i = 0; i < colors.length; i++) - { - var color:uint = colors[i]; - var a:uint = (color & 0xFF000000) >>> 24; - var rgb:uint = (color & 0xFFFFFF); - - if (a == 0 && rgb == bgColor) - { - colors.splice(i, 1); - weights.splice(i, 1); - i--; - continue; - } - - var r:uint = (rgb & 0xFF0000) >>> 16; - var g:uint = (rgb & 0xFF00) >>> 8; - var b:uint = (rgb & 0xFF); - var w = weights[i]; - - rTotal += w * r; - gTotal += w * g; - bTotal += w * b; - - wTotal += w; - } - - if (wTotal == 0) - { - return null; - } - - rTotal /= wTotal; - gTotal /= wTotal; - bTotal /= wTotal; - - var rFinal = Math.max(0, Math.min(255, Math.round(rTotal))); - var gFinal = Math.max(0, Math.min(255, Math.round(gTotal))); - var bFinal = Math.max(0, Math.min(255, Math.round(bTotal))); - - return (uint(rFinal) << 16) | (uint(gFinal) << 8) | (uint(bFinal)); - } - - - - public static function GetExportPNG(bd:BitmapData):ByteArray - { - if (!UseExpandedBitmaps) return PNGEncoder.encode(bd); - - var expanded:BitmapData = ExpandBitmapBorders(bd, 0x0, 2); - - //var fr:FileReference = new FileReference(); - //fr.save(PNGEncoder.encode(expanded), "output.png"); - - return PNGEncoderWithAlpha.encode(expanded, bd); - } - - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/flash/util/RectangleNode.as b/flash/util/RectangleNode.as new file mode 100644 index 0000000..6f31e44 --- /dev/null +++ b/flash/util/RectangleNode.as @@ -0,0 +1,178 @@ +package util { + import flash.geom.Rectangle; + + public class RectangleNode + { + public var Left:RectangleNode = null; + public var Right:RectangleNode = null; + public var Rect:Rectangle = null; + public var InUse:Boolean = false; + public var Removed:Boolean = false; + public var Parent:RectangleNode = null; + public var AllocationID = 0; + public var Host:RectanglePacker= null; + public var MinAllocationID = 0; + public var NodeID; + public static var NextNodeID = 0; + + public var DontRemove = false; + + public var LastAccessTime = 0; + + public var Flags = []; + + public var UpdateTo:RectangleNode = null; + + /* + public function get Removed() + { + return _Removed; + } + + public function set Removed(r) + { + this._Removed = r; + } + + public function get Host():RectanglePacker + { + return _Host; + } + public function set Host(p:RectanglePacker) + { + this._Host = p; + + if (_Left && _Left.Host != p) + { + throw new Error("bad left host"); + } + if (_Right && _Right.Host != p) + { + throw new Error("bad right host"); + } + if (_Parent && _Parent.Host != p) + { + throw new Error("bad parent host"); + } + + } + + public function get Left():RectangleNode + { + return _Left; + } + public function set Left(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad left host"); + } + _Left = n; + } + public function get Right():RectangleNode + { + return _Right; + } + public function set Right(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad right host"); + } + _Right = n; + } + + public function get Parent():RectangleNode + { + return _Parent; + } + public function set Parent(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad parent host"); + } + _Parent = n; + } + */ + public function get IsFreeSpace() + { + return Left == null && Right == null && !InUse; + } + public function UpdateLinksFromNode(node:RectangleNode) + { + if (node.Parent) + { + if (node.Parent.Left == node) + { + node.Parent.Left = this; + } + if (node.Parent.Right == node) + { + node.Parent.Right = this; + } + } + if (node.Left) + { + node.Left.Parent = this; + } + if (node.Right) + { + node.Right.Parent = this; + } + } + public function MakeFromNode(node:RectangleNode) + { + //_Host = node.Host; + Host = node.Host; + Left = node.Left; + Right = node.Right; + Parent = node.Parent; + AllocationID = node.AllocationID; + InUse = node.InUse; + MinAllocationID = node.MinAllocationID; + NodeID = node.NodeID; + Rect = node.Rect.clone(); + Removed = node.Removed; + DontRemove = node.DontRemove; + } + public function RectangleNode(x, y, w, h, host:RectanglePacker) + { + this.NodeID = NextNodeID++; + this.Host = host; + this.Rect = new Rectangle(x, y, w, h); + } + public function OutputJSON() + { + var node = {}; + node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; + node.in_use = InUse; + node.id = NodeID; + if (this.Left) node.left = this.Left.OutputJSON(); + if (this.Right) node.right = this.Right.OutputJSON(); + return node; + } + + public function ReadJSON(details) + { + details.new_node = this; + this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); + this.Removed = false; + + this.InUse = details.in_use; + + if (details.hasOwnProperty("right")) + { + this.Right = new RectangleNode(0, 0, 0, 0, this.Host); + Right.ReadJSON(details.right); + Right.Parent = this; + } + if (details.hasOwnProperty("left")) + { + this.Left = new RectangleNode(0, 0, 0, 0, this.Host); + Left.ReadJSON(details.left); + Left.Parent = this; + } + } + } +} diff --git a/flash/util/RectanglePacker.as b/flash/util/RectanglePacker.as new file mode 100644 index 0000000..597d7fd --- /dev/null +++ b/flash/util/RectanglePacker.as @@ -0,0 +1,562 @@ +package util { + import flash.geom.*; + import flash.display.BitmapData; + import flash.display.MovieClip; + import flash.text.TextField; + import flash.events.*; + import flash.sampler.StackFrame; + + public class RectanglePacker + { + protected var w:int; + protected var h:int; + protected var root:RectangleNode; + public var NextAllocationID = 0; + + public function get width():int { return w; } + public function get height():int { return h; } + + public function RectanglePacker(w, h) + { + this.w = w; + this.h = h; + root = new RectangleNode(0, 0, w, h, this); + root.AllocationID = -1; + } + protected var area = 0; + + protected var testRender:MovieClip = new MovieClip(); + + public function GetRoot():RectangleNode + { + return root; + } + + public function GetLeafNodes():Array + { + return GetLeafNodesInternal(root); + } + + protected function GetLeafNodesInternal(n:RectangleNode):Array + { + if (n.InUse) return [n]; + var ret:Array = new Array(); + if (n.Left) ret = GetLeafNodesInternal(n.Left); + if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); + return ret; + } + + public function GetUsedArea() + { + return area; + } + + public function get efficiency() + { + return area / (w * h); + } + + protected function RectCost(w, h) + { + if (w == 0 || h == 0) return 99999999; + return (Math.max(w, h) / Math.min(w, h)) * w * h; + } + + protected function EnumerateTree(r:RectangleNode = null, indent = "") + { + if (r == null) r = this.root; + var str = ""; + str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; + if (r.Left) str += EnumerateTree(r.Left, indent + " "); + if (r.Right) str += EnumerateTree(r.Left, indent + " "); + return str; + } + + /* + * Remove a list of nodes from the tree. + * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree + * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, + leaving the original objects intact (in case something still references them) + */ + public function RemoveNodes(nodes:Array, fullyDestroy = true) + { + + /* DEBUG CHECKS */ + /* + this.PerformDebugCheck(); + + var str = ""; + for (var i = 0; i < nodes.length; i++) + { + str += nodes[i].NodeID + "\n"; + } + + var orig = nodes.concat(); + + var strs = [str, EnumerateTree()]; + + RenderDetailsBox.StartTrack("PackRemoveTime"); + + for (var i = 0; i < nodes.length; i++) + { + var n:RectangleNode = nodes[i]; + if (n.Host != this) + { + throw new Error("bad host!"); + } + } + */ + /* END DEBUG CHECKS */ + + var i, n:RectangleNode, p:RectangleNode; + + // setup the Removed flag on every node that should be removed + // we also check at this time to see if any more nodes need to be removed, such as a parent of + // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + if (n.Host == this) + { + n.Removed = true; + + if (n.InUse) + { + // sum up the total removed area + area -= n.Rect.width * n.Rect.height; + } + + if (n.Parent != null) + { + p = n.Parent; + // check and see if the current node's parent still has any valid children + if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) + { + // all of the current nodes siblings are either being removed or are blank, so + // we can remove the parent too + if (p.Left.IsFreeSpace) + { + // the left child was empty space before, so we can remove it (if it wasn't + // empty space it is already being removed so it doesn't need to be added + // to the list) + if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); + } + if (p.Right.IsFreeSpace) + { + // the right child was empty space before, so we can remove it + if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); + } + if (p != root && nodes.indexOf(p) == -1) + { + // remove the parent node too (provided it isn't the root!) + nodes.push(p); + } + } + } + } + } + + // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, + // so go ahead and remove them + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + + if (n.Parent != null) + { + // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not + // also getting removed!) + p = n.Parent; + + if (!p.Removed) + { + if (p.Left && p.Right) + { + var newNode:RectangleNode; + if (p.Left.Removed && p.Right.Removed) + { + // both children were removed, but the parent wasn't, so the parent must be root + // (since we never remove the root) + if (p != root) + { + throw new Error("should be root"); + } + p.Left.Parent = null; + p.Right.Parent = null; + p.Left = null; + p.Right = null; + p.InUse = false; + } else if (!p.Left.Removed) { + // Right node removed, Left node not removed + if (!p.Left.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Right); + newNode.UpdateLinksFromNode(p.Right); + } + // Left node is used + p.Right.InUse = false; + p.Right.Left = null; + p.Right.Right = null; + p.Right.Removed = false; + } else { + throw new Error("should have been caught above!"); + } + } else { + // Left node removed, Right node not removed + if (!p.Right.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Left); + newNode.UpdateLinksFromNode(p.Left); + } + // Left node is used + //p.Left.Removed = true; + p.Left.InUse = false; + p.Left.Left = null; + p.Left.Right = null; + p.Left.Removed = false; + //p.Left.Parent = null; + } else { + throw new Error("should have been caught above!"); + } + } + } else { + // huh? how does n.Parent == p but p has no children? something went wrong + throw new Error("shouldn't have gotten here"); + } + } + } + //strs.push(EnumerateTree()); + } + } + + public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode + { + + var node:RectangleNode = FindSizedNode(w, h, root); + + if (node == null) + { + //UHOH, texture full + return null; + } + area += w * h; + node.InUse = true; + + var splitVertFirstCost = 0; + if (w < node.Rect.width) + { + splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); + } + + var splitHorizFirstCost = 0; + if (h < node.Rect.height) + { + splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); + } + + + + if (splitVertFirstCost <= splitHorizFirstCost) + { + node.Flags.push("SplitVertFirst"); + if (w < node.Rect.width) + { + node.Flags.push("SplitVert"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + if (h < node.Rect.height) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + } else { + node.Flags.push("SplitHorzFirst"); + if (h < node.Rect.height) + { + node.Flags.push("SplitVert"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + if (w < node.Rect.width) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + } + NextAllocationID++; + if (useInstead) + { + useInstead.MakeFromNode(node); + useInstead.UpdateLinksFromNode(node); + useInstead.Flags = node.Flags; + node = useInstead; + node.Flags.push("UseInstead"); + } + + //if (!CheckOKNode(node)) node.Flags.push("BadNode"); + + return node; + } + public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) + { + if (r == null) r = this.root; + if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) + { + var ancestor:RectangleNode = FindCommonNode(n, r); + throw new Error("bad node allocated!"); + return false; + } + var ok = true; + if (r.Left) ok = ok && CheckOKNode(n, r.Left); + if (r.Right) ok = ok && CheckOKNode(n, r.Right); + return ok; + } + + public function PerformDebugCheck() + { + DebugInternal(this.root); + } + + protected function DebugInternal(n:RectangleNode) + { + if (n.Host != this) + { + throw new Error("problem with host!"); + } + if (n.IsFreeSpace) + { + if (n.Left || n.Right) + { + throw new Error("shouldn't have children"); + } + } + if ((n.Left && !n.Right) || (n.Right && !n.Left)) + { + throw new Error("mismatched children"); + } + if (n.Left && n.Left.Parent != n) + { + throw new Error("left child has bad parent"); + } + if (n.Right && n.Right.Parent != n) + { + throw new Error("right child has bad parent"); + } + if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) + { + throw new Error("problem with parent"); + } + if (n.Left) DebugInternal(n.Left); + if (n.Right) DebugInternal(n.Right); + } + + public function FindCommonNode(a:RectangleNode, b:RectangleNode) + { + var aHistory = []; + var bHistory = []; + while (a != null) + { + aHistory.push(a); + a = a.Parent; + } + while (b != null) + { + bHistory.push(b); + b = b.Parent; + } + var i = aHistory.length - 1; + var j = bHistory.length - 1; + var same = null; + while (i >= 0 && j >= 0) + { + if (aHistory[i] == bHistory[j]) + { + same = aHistory[i]; + } else { + break; + } + i--; + j--; + } + return same; + } + + public function TestRender() + { + while (testRender.numChildren > 0) + { + testRender.removeChildAt(0); + } + testRender.graphics.clear(); + TestRenderNode(root, testRender); + return testRender; + } + protected function TestRenderNode(n:RectangleNode, m:MovieClip) + { + var g:MovieClip = new MovieClip(); + m.addChild(g); + g.graphics.lineStyle(1, 0, 1); + if (n.Left != null) TestRenderNode(n.Left, m); + if (n.Left != null) TestRenderNode(n.Right, m); + if (n.InUse) + { + g.graphics.beginFill(0xFFFF00, 0.2); + } + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + if (n.InUse) + { + g.graphics.endFill(); + var t:TextField = new TextField(); + t.text = n.NodeID; + t.x = n.Rect.x + n.Rect.width / 2.0; + t.y = n.Rect.y + n.Rect.height / 2.0; + g.addChild(t); + g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); + g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); + } + + } + public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) + { + if (n.InUse) + { + //_trace(Math.round(n.LastAccessTime / 1000)); + } + var p:RectangleNode = n.Parent; + if (p) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); + g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); + g.graphics.endFill(); + t.text = p.NodeID; + if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); + g.oldListener = function(e){MouseOver(p, g, t);}; + g.addEventListener(MouseEvent.CLICK, g.oldListener); + } + } + public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(0xFFFF00, 0.2); + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + g.graphics.endFill(); + t.text = n.NodeID; + } + protected function SplitVert(node:RectangleNode, leftWidth) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function SplitHoriz(node:RectangleNode, topHeight) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode + { + if (node.InUse) return null; + if (node.Rect.width >= w && node.Rect.height >= h) + { + if (node.Left != null && node.Right != null) + { + var t:RectangleNode = FindSizedNode(w, h, node.Left); + if (t != null) return t; + t = FindSizedNode(w, h, node.Right); + return t; + } else { + return node; + } + } + return null; + } + + public function LoadTree(details) + { + this.root = new RectangleNode(0, 0, 0, 0, this); + root.ReadJSON(details); + + this.NextAllocationID = 0; + this.area = 0; + + var queue:Array = new Array(); + queue.push(root); + while (queue.length > 0) + { + var node:RectangleNode = queue.shift(); + node.AllocationID = NextAllocationID; + node.MinAllocationID = NextAllocationID; + if (node.Left) queue.push(node.Left); + if (node.Right) queue.push(node.Right); + if (node.InUse) this.area += node.Rect.width * node.Rect.height; + } + NextAllocationID++; + } + + public function GetNodePath(node:RectangleNode) + { + var output:String = ""; + while (node != this.root) + { + output = (node == node.Parent.Left ? "l" : "r") + output; + node = node.Parent; + } + return output; + } + + public function GetNodeFromPath(path:String):RectangleNode + { + var node:RectangleNode = this.root; + for (var i = 0; i < path.length; i++) + { + if (!node) return null; + if (path.charAt(i) == "r") + { + node = node.Right; + } else { + node = node.Left; + } + } + return node; + } + } +} diff --git a/flash/util/Utils.as b/flash/util/Utils.as new file mode 100644 index 0000000..f792003 --- /dev/null +++ b/flash/util/Utils.as @@ -0,0 +1,389 @@ +package util +{ + import flash.display.*; + import flash.geom.*; + public class Utils + { + public static function GetChildren(clip:MovieClip):Array + { + var ret:Array = []; + for (var i = 0; i < clip.numChildren; i++) + { + ret.push(clip.getChildAt(i)); + } + return ret; + } + + /* + * angle difference + * (range -Math.PI to Math.PI) + */ + public static function GetAngleDiff(a, b) + { + var angleDiff = b - a; + + while (angleDiff > Math.PI) + { + angleDiff -= Math.PI * 2; + } + while (angleDiff < -Math.PI) + { + angleDiff += Math.PI * 2; + } + return angleDiff; + } + + /* + * angle difference + * (range 0 to Math.PI) + */ + public static function GetAngleDiffAbs(a, b) + { + var angleDiff = GetAngleDiff(a, b); + while (angleDiff < 0) + { + angleDiff += Math.PI * 2; + } + + if (angleDiff > Math.PI) + { + angleDiff = Math.PI * 2 - angleDiff; + } + + return angleDiff; + } + + public static function GetTransform(from:Matrix, to:Matrix) + { + var i:Matrix = from.clone(); + i.invert(); + var m:Matrix = to.clone(); + m.concat(i); + return m; + } + + public static function Decompose(m:Matrix) + { + var s:Point = ScaleFromMat(m); + m = m.clone(); + + var sxUnit = s.x >= 0 ? 1 : -1; + var syUnit = s.y >= 0 ? 1 : -1; + + m.scale(sxUnit, syUnit); + + //m.a /= sxUnit; + //m.d /= syUnit; + var rot = RotFromMat(m); + return {sx:s.x, sy:s.y, rot:rot}; + } + + public static function RotFromMat(m:Matrix) + { + return Math.atan2(-m.c, m.a); + } + + public static function ScaleFromMat(m:Matrix):Point + { + var xAxisX = m.a; + var xAxisY = m.c; + + var yAxisX = m.b; + var yAxisY = m.d; + + var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); + if (m.a < 0) sx *= -1; + + var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); + if (m.d < 0) sy *= -1; + + return new Point(sx, sy); + } + + public static function TransformRect(r:Rectangle, m:Matrix) + { + var p1:Point = new Point(r.left, r.top); + var p2:Point = new Point(r.right, r.top); + var p3:Point = new Point(r.left, r.bottom); + var p4:Point = new Point(r.right, r.bottom); + + p1 = m.transformPoint(p1); + p2 = m.transformPoint(p2); + p3 = m.transformPoint(p3); + p4 = m.transformPoint(p4); + + r.left = Math.min(p1.x, p2.x, p3.x, p4.x); + r.top = Math.min(p1.y, p2.y, p3.y, p4.y); + r.right = Math.max(p1.x, p2.x, p3.x, p4.x); + r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); + } + + public static function RoundRect(r:Rectangle) + { + r.left = Math.floor(r.left); + r.top = Math.floor(r.top); + r.right = Math.ceil(r.right); + r.bottom = Math.ceil(r.bottom); + } + + public static function ScaleRect(r:Rectangle, s) + { + r.left *= s; + r.top *= s; + r.right *= s; + r.bottom *= s; + } + + public static function RecursivelyStop(clip) + { + if (clip is MovieClip) + { + clip.stop(); + } + if (clip is DisplayObjectContainer) + { + for (var i = 0; i < clip.numChildren; i++) + { + RecursivelyStop(clip.getChildAt(i)); + } + } + } + + public static function WeirdGotoFrame(clip:MovieClip, frame) + { + var dir = clip.currentFrame > frame ? -1 : 1; + while (clip.currentFrame != frame) + { + RecurseDir(clip, dir); + } + } + + protected static function RecurseDir(clip:MovieClip, dir) + { + for (var i = 0; i < clip.numChildren; i++) + { + var child = clip.getChildAt(i); + if (child is MovieClip) + { + RecurseDir(child, dir); + } + } + if (dir == 1) + { + clip.nextFrame(); + } else { + clip.prevFrame(); + } + } + + protected static var tempSpace:BitmapData = null; + protected static var tempSpaceRect:Rectangle = new Rectangle(); + protected static var tempSpaceMatrix:Matrix = new Matrix(); + protected static var tempSpaceZero:Point = new Point(); + protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); + protected static var lastDrawOffset:Point = new Point(); + public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle + { + if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); + + var oldPad = 0; + var padAmount = 5; + + var ret:Rectangle = new Rectangle(); + + var baseBounds:Rectangle = clip.getBounds(clip); + + var boundsClip:DisplayObject = null; + if (clip is DisplayObjectContainer) + { + boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); + } + + if (boundsClip != null) + { + baseBounds = boundsClip.getBounds(clip); + } + + if (useMatrix) + { + TransformAABBRect(baseBounds, useMatrix); + } + + if (boundsClip != null) + { + return baseBounds; + } + + var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); + var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); + if (tempSpace == null) + { + tempSpace = new BitmapData(minW, minH, true, 0x0); + } + if (tempSpace.width < minW || tempSpace.height < minH) + { + tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); + } + + var r:Rectangle = new Rectangle(); + + baseBounds.left = Math.floor(baseBounds.left); + baseBounds.right = Math.ceil(baseBounds.right); + + baseBounds.top = Math.floor(baseBounds.top); + baseBounds.bottom = Math.ceil(baseBounds.bottom); + + var i; + + var needsChecking = true; + while (needsChecking) + { + needsChecking = false; + r.left = baseBounds.left - padAmount; + r.right = baseBounds.right + padAmount; + + r.top = baseBounds.top - padAmount; + r.bottom = baseBounds.bottom + padAmount; + + ret = r.clone(); + + tempSpaceRect.x = tempSpaceRect.y = 0; + tempSpaceRect.width = tempSpace.width; + tempSpaceRect.height = tempSpace.height; + tempSpace.fillRect(tempSpaceRect, 0x0); + + tempSpaceMatrix.identity(); + if (useMatrix) + { + tempSpaceMatrix.a = useMatrix.a; + tempSpaceMatrix.b = useMatrix.b; + tempSpaceMatrix.c = useMatrix.c; + tempSpaceMatrix.d = useMatrix.d; + tempSpaceMatrix.tx = useMatrix.tx; + tempSpaceMatrix.ty = useMatrix.ty; + } + tempSpaceMatrix.translate(-r.left, -r.top); + + lastDrawOffset.x = -r.left; + lastDrawOffset.y = -r.top; + tempSpace.draw(clip, tempSpaceMatrix); + + tempSpaceRect.width = 1; + tempSpaceRect.height = r.height; + + var sideMovedIn = 0; + for (i = 0; i < r.width; i++) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.left++; + sideMovedIn++; + } + } + if (ret.left < baseBounds.left - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.width - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.right--; + } + } + if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + sideMovedIn = 0; + tempSpaceRect.width = r.width; + tempSpaceRect.height = 1; + tempSpaceRect.x = 0; + for (i = 0; i < r.height; i++) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.top++; + sideMovedIn++; + } + } + if (ret.top < baseBounds.top - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.height - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.bottom--; + } + } + if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + } + return ret; + } + + public static function TransformAABBRect(r:Rectangle, m:Matrix) + { + var o1X = r.left; + var o1Y = r.top; + + var o2X = r.right; + var o2Y = r.top; + + var o3X = r.left; + var o3Y = r.bottom; + + var o4X = r.right; + var o4Y = r.bottom; + + var n1X = o1X * m.a + o1Y * m.c + m.tx; + var n1Y = o1X * m.b + o1Y * m.d + m.ty; + + var n2X = o2X * m.a + o2Y * m.c + m.tx; + var n2Y = o2X * m.b + o2Y * m.d + m.ty; + + var n3X = o3X * m.a + o3Y * m.c + m.tx; + var n3Y = o3X * m.b + o3Y * m.d + m.ty; + + var n4X = o4X * m.a + o4Y * m.c + m.tx; + var n4Y = o4X * m.b + o4Y * m.d + m.ty; + + r.left = Math.min(n1X, n2X, n3X, n4X); + r.right = Math.max(n1X, n2X, n3X, n4X); + + r.top = Math.min(n1Y, n2Y, n3Y, n4Y); + r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); + } + } +} diff --git a/job.py b/job.py index 989c991..77c09e8 100644 --- a/job.py +++ b/job.py @@ -3,6 +3,7 @@ import json from validate import * from args import * +import copy asset_src_schema = { "type":"object", @@ -69,19 +70,24 @@ base_path = os.path.join(self.out_dir, self.rel_path) if not os.path.exists(base_path): os.makedirs(base_path) + resource_names = [] for i,r in enumerate(resources): - path = os.path.join(base_path, "%s_%04d.png" % (self.name, i)) + resource_name = "%s_%04d.png" % (self.name, i) if len(resources) > 1 else self.name + ".png" + resource_names.append(resource_name) + path = os.path.join(base_path, resource_name) with open(path, "wb") as f: f.write(base64.b64decode(r)) if len(data) == 1: graphic_and_asset = {} (name, graphic_data) = data.items()[0] - graphic_and_asset = {"data":graphic_data} + graphic_and_asset = {"data":graphic_data, "resources":resource_names} with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps(graphic_and_asset)) else: + write_data = copy.deepcopy(data) + write_data["resources"] = resource_names with open(os.path.join(base_path, self.name + ".asset"), "w") as f: - f.write(pretty_dumps(data)) + f.write(pretty_dumps(write_data)) for name,details in data.iteritems(): with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps({"data":self.name + ".asset"})) diff --git a/old/Checkbox.as b/old/Checkbox.as deleted file mode 100644 index c5aaba2..0000000 --- a/old/Checkbox.as +++ /dev/null @@ -1,42 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - - public class Checkbox extends MovieClip - { - public var Enabled:Boolean = true; - public function Checkbox() - { - checkbox.gotoAndStop(1); - checkbox.addEventListener(MouseEvent.CLICK, Clicked); - } - - protected function Clicked(event) - { - if (!Enabled) return; - Toggle(); - if (OnClick != null) OnClick(OnClickParam); - } - - protected var checked = false; - public function set Checked(value) { checked = value; checkbox.gotoAndStop(checked ? 2 : 1); } - public function get Checked() { return checked; } - - public function set Text(value) { text.text = value; } - - public var OnClickParam; - public var OnClick; - - - public function Toggle() - { - checked = !checked; - checkbox.gotoAndStop(checked ? 2 : 1); - - - } - - } - -} diff --git a/old/GraphicExport-app.xml b/old/GraphicExport-app.xml deleted file mode 100644 index 5144634..0000000 --- a/old/GraphicExport-app.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - GraphicExport - 1.0 - GraphicExport - - GraphicExport - - - GraphicExport.swf - standard - false - true - false - portrait - auto - true - true - true - - - false - false - desktop extendedDesktop diff --git a/old/GraphicExport.exe b/old/GraphicExport.exe deleted file mode 100644 index 56315aa..0000000 --- a/old/GraphicExport.exe +++ /dev/null Binary files differ diff --git a/old/GraphicExport.fla b/old/GraphicExport.fla deleted file mode 100644 index 0b78ed7..0000000 --- a/old/GraphicExport.fla +++ /dev/null Binary files differ diff --git a/old/GraphicExport.swf b/old/GraphicExport.swf deleted file mode 100644 index 542db97..0000000 --- a/old/GraphicExport.swf +++ /dev/null Binary files differ diff --git a/old/NewGraphicDialog.as b/old/NewGraphicDialog.as deleted file mode 100644 index 152011c..0000000 --- a/old/NewGraphicDialog.as +++ /dev/null @@ -1,224 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - import flash.events.*; - import flash.filesystem.File; - import flash.net.FileFilter; - import Defs.GraphicDef; - import flash.text.engine.GraphicElement; - - public class NewGraphicDialog extends MovieClip - { - - public function NewGraphicDialog() - { - // constructor code - Init(); - } - - var typeButtons:Array = new Array(); - - public function Init() - { - graphicPath.text = "Path to Graphic Here"; - - this.removeChild(browseButton); - - var newBrowseButton = new UI_GenericBlueButton(); - newBrowseButton.Text = "Browse"; - newBrowseButton.OnClick = BrowseForFile; - newBrowseButton.x = browseButton.x + (newBrowseButton.width / 2); - newBrowseButton.y = browseButton.y + (newBrowseButton.height / 2); - addChild(newBrowseButton); - - var newTestButton = new UI_GenericBlueButton(); - newTestButton.Text = "Export"; - newTestButton.OnClick = TestFile; - newTestButton.x = testButton.x + (newTestButton.width / 2); - newTestButton.y = testButton.y + (newTestButton.height / 2); - addChild(newTestButton); - - this.removeChild(typePlaceholderButton); - - var typeX = typePlaceholderButton.x; - var typeY = typePlaceholderButton.y + (typePlaceholderButton.height / 2); - - - var typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Graphic (1)"; - typeButton.OnClick = function(){ SetType(1); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Skeletal (3)"; - typeButton.OnClick = function(){ SetType(3); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Scene (6)"; - typeButton.OnClick = function(){ SetType(6); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - animationCheckbox.Checked = true; - //browseButton - //typePlaceholderButton - //usesInput - //usesText.text = "" - } - - var usesInputDefaultText = "Comma Seperated List of Uses Here"; - - public static var fakeID = 9999999; - public function TestFile() - { - fakeID++; - var graphicName = graphicPath.text; - var graphicData = {id:fakeID,graphic:graphicPath.text,v:1,fs:0,p:0,type:selectedType}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new GraphicDef(graphicData); - - this.Hide(); - graphicExport.ExportItem(graphicDef); - } - - var selectedType = 1; - public function SetType(type:Number) - { - selectedType = type; - - for(var i = 0; i < typeButtons.length; i++) - { - typeButtons[i].Enabled = true; - } - - animationCheckbox.visible = false; - - switch(type) - { - case 1: { - typeButtons[0].Enabled = false; - animationCheckbox.visible = true; - break; - } - case 3: typeButtons[1].Enabled = false; break; - case 6: typeButtons[2].Enabled = false; break; - } - } - - var graphicExport:GraphicExport; - public function Show(parentClip) - { - this.graphicExport = parentClip; - - parentClip.addChild(this); - - SetType(selectedType); - - var graphicList = GameData.Instance().GraphicDefines; - - var usesString:String = ""; - var uniqueUseTypes:Array = new Array(); - for (var i = 0; i < graphicList.length; i++) - { - var graphicDef:GraphicDef = graphicList[i]; - var uses = graphicDef.ExportParams['uses']; - for (var usage in uses) - { - if (uniqueUseTypes[uses[usage]] == null) - { - uniqueUseTypes[uses[usage]] = uses[usage]; - usesString += uses[usage] + ", "; - } - } - } - - graphicPath.text = ""; - - } - - public function CloseClicked(event) - { - Hide(); - } - - public function Hide() - { - if (this.parent != null) this.parent.removeChild(this); - } - - public function BrowseForFile() - { - var file:File = new File(); - var swfTypeFilter:FileFilter = new FileFilter("SWF Files","*.swf"); - file.addEventListener(Event.SELECT, openFile); - file.browse([swfTypeFilter]); - } - - private function openFile(event:Event):void - { - _strace(event.target.nativePath); - var path:String = event.target.nativePath; - var pathParts:Array = path.split("Graphics\\"); - if (pathParts.length == 2) - { - var fileRemainder:String = pathParts[1]; - var withoutExtension:String = fileRemainder.split(".")[0]; - var pattern:RegExp = /\\/g; - withoutExtension = withoutExtension.replace(pattern, "/"); - _strace(withoutExtension); - graphicPath.text = withoutExtension; - - if (withoutExtension.indexOf("Backgrounds") > -1) - { - SetType(6); - } - - if (withoutExtension.indexOf("Monsters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Characters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Portraits") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Quest") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Equipment") > -1) - { - SetType(1); - } - - - } - } - - - } - -} diff --git a/old/PNGExportHelper.as b/old/PNGExportHelper.as deleted file mode 100644 index f8c4c9d..0000000 --- a/old/PNGExportHelper.as +++ /dev/null @@ -1,253 +0,0 @@ -package -{ - import flash.display.*; - import com.adobe.images.*; - import flash.utils.*; - import flash.net.*; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import flash.geom.Point; - - public class PNGExportHelper - { - public static var UseExpandedBitmaps = false; - public static var AlphaThreshold = 5; - - private static function ExpandBitmapBorders(bd:BitmapData, bgColor = 0x0, passes = 1):BitmapData - { - /* - var thresh:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - thresh.threshold(bd, bd.rect, new Point(), "<", (20 << 24), bgColor, 0xFF000000, true); - */ - var sampled:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - bd.lock(); - sampled.lock(); - - for (var y = 0; y < bd.height; y++) - { - for (var x = 0; x < bd.width; x++) - { - var oldVal:uint = bd.getPixel32(x, y); - var a:uint = (oldVal & 0xFF000000) >>> 24; - var rgb:uint = (oldVal & 0xFFFFFF); - if (a > AlphaThreshold) - { - sampled.setPixel32(x, y, (0xFF << 24) | rgb); - } - else - { - sampled.setPixel32(x, y, bgColor); - } - } - } - sampled.unlock(); - bd.unlock(); - - return ExpandBitmapBordersInternal(sampled, bgColor, passes); - } - - private static function ExpandBitmapBordersInternal(bd:BitmapData, bgColor, passes):BitmapData - { - var output:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - - var scale = 16; - var scaled:BitmapData = new BitmapData(bd.width/scale, bd.height/scale, true, bgColor); - var mat:Matrix = new Matrix(); - mat.scale(1/scale, 1/scale); - scaled.draw(bd, mat, null, null, null, true); - - output.lock(); - - var colors:Array = new Array(); - var weights:Array = new Array(); - - for (var oy = 0; oy < scaled.height; oy++) - { - - for (var ox = 0; ox < scaled.width; ox++) - { - - var scaledVal:uint = scaled.getPixel32(ox, oy); - var scaleda:uint = (scaledVal & 0xFF000000) >>> 24; - if (scaleda == 0 || scaleda == 255) - { - output.copyPixels(bd, new Rectangle(ox * scale, oy * scale, scale, scale), new Point(ox * scale, oy * scale)); - continue; - } else { - //_strace(scaleda+""); - } - - - for (var y = oy * scale; y < oy * scale + scale; y++) - { - for (var x = ox * scale; x < ox * scale + scale; x++) - { - var oldVal:uint = bd.getPixel32(x, y); - var a:uint = (oldVal & 0xFF000000) >>> 24; - var rgb:uint = (oldVal & 0xFFFFFF); - - if (a == 0 && rgb == bgColor) - { - colors.length = 0; - weights.length = 0; - - for (var y1 = y - 2; y1 <= y + 2; y1++) - { - for (var x1 = x - 2; x1 <= x + 2; x1++) - { - var dist = Math.abs(x1 - x) + Math.abs(y1 - y); - if (dist >= 3) continue; - - if (x1 >= 0 && x1 < bd.width && y1 >= 0 && y1 < bd.height) - { - colors.push(bd.getPixel(x1, y1)); - weights.push(1 - dist * 0.2); - } - } - } - - var newVal = AveragePixels(colors, weights, bgColor); - if (newVal == null) - { - newVal = oldVal; - } - else - { - var newR:uint = (newVal & 0xFF0000) >> 16; - var newG:uint = (newVal & 0xFF00) >> 8; - var newB:uint = (newVal & 0xFF); - - if (newVal != 0 && colors.length >= 4) - { - var bp = true; - } - - var sorted = colors.sort(function(a, b) - { - var aR:uint = (a & 0xFF0000) >> 16; - var aG:uint = (a & 0xFF00) >> 8; - var aB:uint = (a & 0xFF); - - var bR:uint = (b & 0xFF0000) >> 16; - var bG:uint = (b & 0xFF00) >> 8; - var bB:uint = (b & 0xFF); - - var diffA = Math.abs(aR - newR) + Math.abs(aG - newG) + Math.abs(aB - newB); - var diffB = Math.abs(bR - newR) + Math.abs(bG - newG) + Math.abs(bB - newB); - - return diffA - diffB; - - }, Array.RETURNINDEXEDARRAY | Array.DESCENDING); - - var toRemove = Math.min(2, colors.length - 4); - var removed = 0; - for (var i = 0; i < colors.length; i++) - { - var index = sorted.indexOf(i + removed); - if (index < toRemove) - { - colors.splice(i, 1); - weights.splice(i, 1); - removed++; - i--; - if (removed == toRemove) break; - } - } - - var fixOutliersVal = AveragePixels(colors, weights, bgColor); - if (fixOutliersVal == null) newVal = (0xFF << 24) | newVal; - - newVal = (0xFF << 24) | fixOutliersVal; - } - - output.setPixel32(x, y, newVal); - } - else - { - output.setPixel32(x, y, oldVal); - } - } - } - }//end outer scaled x - }//End outer scaled y - - bd.unlock(); - output.unlock(); - - passes--; - if (passes > 0) - { - return ExpandBitmapBordersInternal(output, bgColor, passes); - } - else - { - return output; - } - } - - private static function AveragePixels(colors:Array, weights:Array, bgColor:uint):uint - { - var rTotal = 0; - var gTotal = 0; - var bTotal = 0; - - var wTotal = 0; - - for (var i = 0; i < colors.length; i++) - { - var color:uint = colors[i]; - var a:uint = (color & 0xFF000000) >>> 24; - var rgb:uint = (color & 0xFFFFFF); - - if (a == 0 && rgb == bgColor) - { - colors.splice(i, 1); - weights.splice(i, 1); - i--; - continue; - } - - var r:uint = (rgb & 0xFF0000) >>> 16; - var g:uint = (rgb & 0xFF00) >>> 8; - var b:uint = (rgb & 0xFF); - var w = weights[i]; - - rTotal += w * r; - gTotal += w * g; - bTotal += w * b; - - wTotal += w; - } - - if (wTotal == 0) - { - return null; - } - - rTotal /= wTotal; - gTotal /= wTotal; - bTotal /= wTotal; - - var rFinal = Math.max(0, Math.min(255, Math.round(rTotal))); - var gFinal = Math.max(0, Math.min(255, Math.round(gTotal))); - var bFinal = Math.max(0, Math.min(255, Math.round(bTotal))); - - return (uint(rFinal) << 16) | (uint(gFinal) << 8) | (uint(bFinal)); - } - - - - public static function GetExportPNG(bd:BitmapData):ByteArray - { - if (!UseExpandedBitmaps) return PNGEncoder.encode(bd); - - var expanded:BitmapData = ExpandBitmapBorders(bd, 0x0, 2); - - //var fr:FileReference = new FileReference(); - //fr.save(PNGEncoder.encode(expanded), "output.png"); - - return PNGEncoderWithAlpha.encode(expanded, bd); - } - - } -} \ No newline at end of file diff --git a/old/PreviewHolder.as b/old/PreviewHolder.as deleted file mode 100644 index 587bf68..0000000 --- a/old/PreviewHolder.as +++ /dev/null @@ -1,57 +0,0 @@ -package { - import flash.display.MovieClip; - - public class PreviewHolder extends MovieClip - { - - var startingWidth = 1024; - var startingHeight = 1024; - - public function PreviewHolder() - { - startingWidth = this.width; - startingHeight = this.height; - } - - var clips:Array = new Array(); - public function AddClip(clip) - { - clips.push(clip); - this.addChild(clip); - ArrangeClips(); - } - - public function ArrangeClips() - { - var numCols = Math.ceil(Math.sqrt(clips.length)); - var maxY = 0; - var maxX = 0; - var clipIndex = 0; - for (var row = 0; row < numCols; row++) - { - var clipX = 0; - var clipY = maxY; - for (var col = 0; col < numCols; col++) - { - if (clipIndex == clips.length) break; - clips[clipIndex].x = clipX; - clips[clipIndex].y = clipY; - clipX += clips[clipIndex].width; - var clipBottom = clips[clipIndex].y + clips[clipIndex].height; - if (clipBottom > maxY) maxY = clipBottom; - - var clipRight = clips[clipIndex].x + clips[clipIndex].width; - if (clipRight > maxX) maxX = clipRight; - clipIndex++; - } - } - - var scale = Math.min(startingWidth / maxX, startingHeight / maxY); - if (scale > 1) scale = 1; - - this.scaleX = this.scaleY = scale; - } - - } - -} diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/flash/util/RectangleNode.as b/flash/util/RectangleNode.as new file mode 100644 index 0000000..6f31e44 --- /dev/null +++ b/flash/util/RectangleNode.as @@ -0,0 +1,178 @@ +package util { + import flash.geom.Rectangle; + + public class RectangleNode + { + public var Left:RectangleNode = null; + public var Right:RectangleNode = null; + public var Rect:Rectangle = null; + public var InUse:Boolean = false; + public var Removed:Boolean = false; + public var Parent:RectangleNode = null; + public var AllocationID = 0; + public var Host:RectanglePacker= null; + public var MinAllocationID = 0; + public var NodeID; + public static var NextNodeID = 0; + + public var DontRemove = false; + + public var LastAccessTime = 0; + + public var Flags = []; + + public var UpdateTo:RectangleNode = null; + + /* + public function get Removed() + { + return _Removed; + } + + public function set Removed(r) + { + this._Removed = r; + } + + public function get Host():RectanglePacker + { + return _Host; + } + public function set Host(p:RectanglePacker) + { + this._Host = p; + + if (_Left && _Left.Host != p) + { + throw new Error("bad left host"); + } + if (_Right && _Right.Host != p) + { + throw new Error("bad right host"); + } + if (_Parent && _Parent.Host != p) + { + throw new Error("bad parent host"); + } + + } + + public function get Left():RectangleNode + { + return _Left; + } + public function set Left(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad left host"); + } + _Left = n; + } + public function get Right():RectangleNode + { + return _Right; + } + public function set Right(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad right host"); + } + _Right = n; + } + + public function get Parent():RectangleNode + { + return _Parent; + } + public function set Parent(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad parent host"); + } + _Parent = n; + } + */ + public function get IsFreeSpace() + { + return Left == null && Right == null && !InUse; + } + public function UpdateLinksFromNode(node:RectangleNode) + { + if (node.Parent) + { + if (node.Parent.Left == node) + { + node.Parent.Left = this; + } + if (node.Parent.Right == node) + { + node.Parent.Right = this; + } + } + if (node.Left) + { + node.Left.Parent = this; + } + if (node.Right) + { + node.Right.Parent = this; + } + } + public function MakeFromNode(node:RectangleNode) + { + //_Host = node.Host; + Host = node.Host; + Left = node.Left; + Right = node.Right; + Parent = node.Parent; + AllocationID = node.AllocationID; + InUse = node.InUse; + MinAllocationID = node.MinAllocationID; + NodeID = node.NodeID; + Rect = node.Rect.clone(); + Removed = node.Removed; + DontRemove = node.DontRemove; + } + public function RectangleNode(x, y, w, h, host:RectanglePacker) + { + this.NodeID = NextNodeID++; + this.Host = host; + this.Rect = new Rectangle(x, y, w, h); + } + public function OutputJSON() + { + var node = {}; + node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; + node.in_use = InUse; + node.id = NodeID; + if (this.Left) node.left = this.Left.OutputJSON(); + if (this.Right) node.right = this.Right.OutputJSON(); + return node; + } + + public function ReadJSON(details) + { + details.new_node = this; + this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); + this.Removed = false; + + this.InUse = details.in_use; + + if (details.hasOwnProperty("right")) + { + this.Right = new RectangleNode(0, 0, 0, 0, this.Host); + Right.ReadJSON(details.right); + Right.Parent = this; + } + if (details.hasOwnProperty("left")) + { + this.Left = new RectangleNode(0, 0, 0, 0, this.Host); + Left.ReadJSON(details.left); + Left.Parent = this; + } + } + } +} diff --git a/flash/util/RectanglePacker.as b/flash/util/RectanglePacker.as new file mode 100644 index 0000000..597d7fd --- /dev/null +++ b/flash/util/RectanglePacker.as @@ -0,0 +1,562 @@ +package util { + import flash.geom.*; + import flash.display.BitmapData; + import flash.display.MovieClip; + import flash.text.TextField; + import flash.events.*; + import flash.sampler.StackFrame; + + public class RectanglePacker + { + protected var w:int; + protected var h:int; + protected var root:RectangleNode; + public var NextAllocationID = 0; + + public function get width():int { return w; } + public function get height():int { return h; } + + public function RectanglePacker(w, h) + { + this.w = w; + this.h = h; + root = new RectangleNode(0, 0, w, h, this); + root.AllocationID = -1; + } + protected var area = 0; + + protected var testRender:MovieClip = new MovieClip(); + + public function GetRoot():RectangleNode + { + return root; + } + + public function GetLeafNodes():Array + { + return GetLeafNodesInternal(root); + } + + protected function GetLeafNodesInternal(n:RectangleNode):Array + { + if (n.InUse) return [n]; + var ret:Array = new Array(); + if (n.Left) ret = GetLeafNodesInternal(n.Left); + if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); + return ret; + } + + public function GetUsedArea() + { + return area; + } + + public function get efficiency() + { + return area / (w * h); + } + + protected function RectCost(w, h) + { + if (w == 0 || h == 0) return 99999999; + return (Math.max(w, h) / Math.min(w, h)) * w * h; + } + + protected function EnumerateTree(r:RectangleNode = null, indent = "") + { + if (r == null) r = this.root; + var str = ""; + str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; + if (r.Left) str += EnumerateTree(r.Left, indent + " "); + if (r.Right) str += EnumerateTree(r.Left, indent + " "); + return str; + } + + /* + * Remove a list of nodes from the tree. + * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree + * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, + leaving the original objects intact (in case something still references them) + */ + public function RemoveNodes(nodes:Array, fullyDestroy = true) + { + + /* DEBUG CHECKS */ + /* + this.PerformDebugCheck(); + + var str = ""; + for (var i = 0; i < nodes.length; i++) + { + str += nodes[i].NodeID + "\n"; + } + + var orig = nodes.concat(); + + var strs = [str, EnumerateTree()]; + + RenderDetailsBox.StartTrack("PackRemoveTime"); + + for (var i = 0; i < nodes.length; i++) + { + var n:RectangleNode = nodes[i]; + if (n.Host != this) + { + throw new Error("bad host!"); + } + } + */ + /* END DEBUG CHECKS */ + + var i, n:RectangleNode, p:RectangleNode; + + // setup the Removed flag on every node that should be removed + // we also check at this time to see if any more nodes need to be removed, such as a parent of + // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + if (n.Host == this) + { + n.Removed = true; + + if (n.InUse) + { + // sum up the total removed area + area -= n.Rect.width * n.Rect.height; + } + + if (n.Parent != null) + { + p = n.Parent; + // check and see if the current node's parent still has any valid children + if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) + { + // all of the current nodes siblings are either being removed or are blank, so + // we can remove the parent too + if (p.Left.IsFreeSpace) + { + // the left child was empty space before, so we can remove it (if it wasn't + // empty space it is already being removed so it doesn't need to be added + // to the list) + if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); + } + if (p.Right.IsFreeSpace) + { + // the right child was empty space before, so we can remove it + if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); + } + if (p != root && nodes.indexOf(p) == -1) + { + // remove the parent node too (provided it isn't the root!) + nodes.push(p); + } + } + } + } + } + + // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, + // so go ahead and remove them + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + + if (n.Parent != null) + { + // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not + // also getting removed!) + p = n.Parent; + + if (!p.Removed) + { + if (p.Left && p.Right) + { + var newNode:RectangleNode; + if (p.Left.Removed && p.Right.Removed) + { + // both children were removed, but the parent wasn't, so the parent must be root + // (since we never remove the root) + if (p != root) + { + throw new Error("should be root"); + } + p.Left.Parent = null; + p.Right.Parent = null; + p.Left = null; + p.Right = null; + p.InUse = false; + } else if (!p.Left.Removed) { + // Right node removed, Left node not removed + if (!p.Left.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Right); + newNode.UpdateLinksFromNode(p.Right); + } + // Left node is used + p.Right.InUse = false; + p.Right.Left = null; + p.Right.Right = null; + p.Right.Removed = false; + } else { + throw new Error("should have been caught above!"); + } + } else { + // Left node removed, Right node not removed + if (!p.Right.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Left); + newNode.UpdateLinksFromNode(p.Left); + } + // Left node is used + //p.Left.Removed = true; + p.Left.InUse = false; + p.Left.Left = null; + p.Left.Right = null; + p.Left.Removed = false; + //p.Left.Parent = null; + } else { + throw new Error("should have been caught above!"); + } + } + } else { + // huh? how does n.Parent == p but p has no children? something went wrong + throw new Error("shouldn't have gotten here"); + } + } + } + //strs.push(EnumerateTree()); + } + } + + public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode + { + + var node:RectangleNode = FindSizedNode(w, h, root); + + if (node == null) + { + //UHOH, texture full + return null; + } + area += w * h; + node.InUse = true; + + var splitVertFirstCost = 0; + if (w < node.Rect.width) + { + splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); + } + + var splitHorizFirstCost = 0; + if (h < node.Rect.height) + { + splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); + } + + + + if (splitVertFirstCost <= splitHorizFirstCost) + { + node.Flags.push("SplitVertFirst"); + if (w < node.Rect.width) + { + node.Flags.push("SplitVert"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + if (h < node.Rect.height) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + } else { + node.Flags.push("SplitHorzFirst"); + if (h < node.Rect.height) + { + node.Flags.push("SplitVert"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + if (w < node.Rect.width) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + } + NextAllocationID++; + if (useInstead) + { + useInstead.MakeFromNode(node); + useInstead.UpdateLinksFromNode(node); + useInstead.Flags = node.Flags; + node = useInstead; + node.Flags.push("UseInstead"); + } + + //if (!CheckOKNode(node)) node.Flags.push("BadNode"); + + return node; + } + public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) + { + if (r == null) r = this.root; + if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) + { + var ancestor:RectangleNode = FindCommonNode(n, r); + throw new Error("bad node allocated!"); + return false; + } + var ok = true; + if (r.Left) ok = ok && CheckOKNode(n, r.Left); + if (r.Right) ok = ok && CheckOKNode(n, r.Right); + return ok; + } + + public function PerformDebugCheck() + { + DebugInternal(this.root); + } + + protected function DebugInternal(n:RectangleNode) + { + if (n.Host != this) + { + throw new Error("problem with host!"); + } + if (n.IsFreeSpace) + { + if (n.Left || n.Right) + { + throw new Error("shouldn't have children"); + } + } + if ((n.Left && !n.Right) || (n.Right && !n.Left)) + { + throw new Error("mismatched children"); + } + if (n.Left && n.Left.Parent != n) + { + throw new Error("left child has bad parent"); + } + if (n.Right && n.Right.Parent != n) + { + throw new Error("right child has bad parent"); + } + if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) + { + throw new Error("problem with parent"); + } + if (n.Left) DebugInternal(n.Left); + if (n.Right) DebugInternal(n.Right); + } + + public function FindCommonNode(a:RectangleNode, b:RectangleNode) + { + var aHistory = []; + var bHistory = []; + while (a != null) + { + aHistory.push(a); + a = a.Parent; + } + while (b != null) + { + bHistory.push(b); + b = b.Parent; + } + var i = aHistory.length - 1; + var j = bHistory.length - 1; + var same = null; + while (i >= 0 && j >= 0) + { + if (aHistory[i] == bHistory[j]) + { + same = aHistory[i]; + } else { + break; + } + i--; + j--; + } + return same; + } + + public function TestRender() + { + while (testRender.numChildren > 0) + { + testRender.removeChildAt(0); + } + testRender.graphics.clear(); + TestRenderNode(root, testRender); + return testRender; + } + protected function TestRenderNode(n:RectangleNode, m:MovieClip) + { + var g:MovieClip = new MovieClip(); + m.addChild(g); + g.graphics.lineStyle(1, 0, 1); + if (n.Left != null) TestRenderNode(n.Left, m); + if (n.Left != null) TestRenderNode(n.Right, m); + if (n.InUse) + { + g.graphics.beginFill(0xFFFF00, 0.2); + } + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + if (n.InUse) + { + g.graphics.endFill(); + var t:TextField = new TextField(); + t.text = n.NodeID; + t.x = n.Rect.x + n.Rect.width / 2.0; + t.y = n.Rect.y + n.Rect.height / 2.0; + g.addChild(t); + g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); + g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); + } + + } + public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) + { + if (n.InUse) + { + //_trace(Math.round(n.LastAccessTime / 1000)); + } + var p:RectangleNode = n.Parent; + if (p) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); + g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); + g.graphics.endFill(); + t.text = p.NodeID; + if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); + g.oldListener = function(e){MouseOver(p, g, t);}; + g.addEventListener(MouseEvent.CLICK, g.oldListener); + } + } + public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(0xFFFF00, 0.2); + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + g.graphics.endFill(); + t.text = n.NodeID; + } + protected function SplitVert(node:RectangleNode, leftWidth) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function SplitHoriz(node:RectangleNode, topHeight) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode + { + if (node.InUse) return null; + if (node.Rect.width >= w && node.Rect.height >= h) + { + if (node.Left != null && node.Right != null) + { + var t:RectangleNode = FindSizedNode(w, h, node.Left); + if (t != null) return t; + t = FindSizedNode(w, h, node.Right); + return t; + } else { + return node; + } + } + return null; + } + + public function LoadTree(details) + { + this.root = new RectangleNode(0, 0, 0, 0, this); + root.ReadJSON(details); + + this.NextAllocationID = 0; + this.area = 0; + + var queue:Array = new Array(); + queue.push(root); + while (queue.length > 0) + { + var node:RectangleNode = queue.shift(); + node.AllocationID = NextAllocationID; + node.MinAllocationID = NextAllocationID; + if (node.Left) queue.push(node.Left); + if (node.Right) queue.push(node.Right); + if (node.InUse) this.area += node.Rect.width * node.Rect.height; + } + NextAllocationID++; + } + + public function GetNodePath(node:RectangleNode) + { + var output:String = ""; + while (node != this.root) + { + output = (node == node.Parent.Left ? "l" : "r") + output; + node = node.Parent; + } + return output; + } + + public function GetNodeFromPath(path:String):RectangleNode + { + var node:RectangleNode = this.root; + for (var i = 0; i < path.length; i++) + { + if (!node) return null; + if (path.charAt(i) == "r") + { + node = node.Right; + } else { + node = node.Left; + } + } + return node; + } + } +} diff --git a/flash/util/Utils.as b/flash/util/Utils.as new file mode 100644 index 0000000..f792003 --- /dev/null +++ b/flash/util/Utils.as @@ -0,0 +1,389 @@ +package util +{ + import flash.display.*; + import flash.geom.*; + public class Utils + { + public static function GetChildren(clip:MovieClip):Array + { + var ret:Array = []; + for (var i = 0; i < clip.numChildren; i++) + { + ret.push(clip.getChildAt(i)); + } + return ret; + } + + /* + * angle difference + * (range -Math.PI to Math.PI) + */ + public static function GetAngleDiff(a, b) + { + var angleDiff = b - a; + + while (angleDiff > Math.PI) + { + angleDiff -= Math.PI * 2; + } + while (angleDiff < -Math.PI) + { + angleDiff += Math.PI * 2; + } + return angleDiff; + } + + /* + * angle difference + * (range 0 to Math.PI) + */ + public static function GetAngleDiffAbs(a, b) + { + var angleDiff = GetAngleDiff(a, b); + while (angleDiff < 0) + { + angleDiff += Math.PI * 2; + } + + if (angleDiff > Math.PI) + { + angleDiff = Math.PI * 2 - angleDiff; + } + + return angleDiff; + } + + public static function GetTransform(from:Matrix, to:Matrix) + { + var i:Matrix = from.clone(); + i.invert(); + var m:Matrix = to.clone(); + m.concat(i); + return m; + } + + public static function Decompose(m:Matrix) + { + var s:Point = ScaleFromMat(m); + m = m.clone(); + + var sxUnit = s.x >= 0 ? 1 : -1; + var syUnit = s.y >= 0 ? 1 : -1; + + m.scale(sxUnit, syUnit); + + //m.a /= sxUnit; + //m.d /= syUnit; + var rot = RotFromMat(m); + return {sx:s.x, sy:s.y, rot:rot}; + } + + public static function RotFromMat(m:Matrix) + { + return Math.atan2(-m.c, m.a); + } + + public static function ScaleFromMat(m:Matrix):Point + { + var xAxisX = m.a; + var xAxisY = m.c; + + var yAxisX = m.b; + var yAxisY = m.d; + + var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); + if (m.a < 0) sx *= -1; + + var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); + if (m.d < 0) sy *= -1; + + return new Point(sx, sy); + } + + public static function TransformRect(r:Rectangle, m:Matrix) + { + var p1:Point = new Point(r.left, r.top); + var p2:Point = new Point(r.right, r.top); + var p3:Point = new Point(r.left, r.bottom); + var p4:Point = new Point(r.right, r.bottom); + + p1 = m.transformPoint(p1); + p2 = m.transformPoint(p2); + p3 = m.transformPoint(p3); + p4 = m.transformPoint(p4); + + r.left = Math.min(p1.x, p2.x, p3.x, p4.x); + r.top = Math.min(p1.y, p2.y, p3.y, p4.y); + r.right = Math.max(p1.x, p2.x, p3.x, p4.x); + r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); + } + + public static function RoundRect(r:Rectangle) + { + r.left = Math.floor(r.left); + r.top = Math.floor(r.top); + r.right = Math.ceil(r.right); + r.bottom = Math.ceil(r.bottom); + } + + public static function ScaleRect(r:Rectangle, s) + { + r.left *= s; + r.top *= s; + r.right *= s; + r.bottom *= s; + } + + public static function RecursivelyStop(clip) + { + if (clip is MovieClip) + { + clip.stop(); + } + if (clip is DisplayObjectContainer) + { + for (var i = 0; i < clip.numChildren; i++) + { + RecursivelyStop(clip.getChildAt(i)); + } + } + } + + public static function WeirdGotoFrame(clip:MovieClip, frame) + { + var dir = clip.currentFrame > frame ? -1 : 1; + while (clip.currentFrame != frame) + { + RecurseDir(clip, dir); + } + } + + protected static function RecurseDir(clip:MovieClip, dir) + { + for (var i = 0; i < clip.numChildren; i++) + { + var child = clip.getChildAt(i); + if (child is MovieClip) + { + RecurseDir(child, dir); + } + } + if (dir == 1) + { + clip.nextFrame(); + } else { + clip.prevFrame(); + } + } + + protected static var tempSpace:BitmapData = null; + protected static var tempSpaceRect:Rectangle = new Rectangle(); + protected static var tempSpaceMatrix:Matrix = new Matrix(); + protected static var tempSpaceZero:Point = new Point(); + protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); + protected static var lastDrawOffset:Point = new Point(); + public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle + { + if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); + + var oldPad = 0; + var padAmount = 5; + + var ret:Rectangle = new Rectangle(); + + var baseBounds:Rectangle = clip.getBounds(clip); + + var boundsClip:DisplayObject = null; + if (clip is DisplayObjectContainer) + { + boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); + } + + if (boundsClip != null) + { + baseBounds = boundsClip.getBounds(clip); + } + + if (useMatrix) + { + TransformAABBRect(baseBounds, useMatrix); + } + + if (boundsClip != null) + { + return baseBounds; + } + + var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); + var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); + if (tempSpace == null) + { + tempSpace = new BitmapData(minW, minH, true, 0x0); + } + if (tempSpace.width < minW || tempSpace.height < minH) + { + tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); + } + + var r:Rectangle = new Rectangle(); + + baseBounds.left = Math.floor(baseBounds.left); + baseBounds.right = Math.ceil(baseBounds.right); + + baseBounds.top = Math.floor(baseBounds.top); + baseBounds.bottom = Math.ceil(baseBounds.bottom); + + var i; + + var needsChecking = true; + while (needsChecking) + { + needsChecking = false; + r.left = baseBounds.left - padAmount; + r.right = baseBounds.right + padAmount; + + r.top = baseBounds.top - padAmount; + r.bottom = baseBounds.bottom + padAmount; + + ret = r.clone(); + + tempSpaceRect.x = tempSpaceRect.y = 0; + tempSpaceRect.width = tempSpace.width; + tempSpaceRect.height = tempSpace.height; + tempSpace.fillRect(tempSpaceRect, 0x0); + + tempSpaceMatrix.identity(); + if (useMatrix) + { + tempSpaceMatrix.a = useMatrix.a; + tempSpaceMatrix.b = useMatrix.b; + tempSpaceMatrix.c = useMatrix.c; + tempSpaceMatrix.d = useMatrix.d; + tempSpaceMatrix.tx = useMatrix.tx; + tempSpaceMatrix.ty = useMatrix.ty; + } + tempSpaceMatrix.translate(-r.left, -r.top); + + lastDrawOffset.x = -r.left; + lastDrawOffset.y = -r.top; + tempSpace.draw(clip, tempSpaceMatrix); + + tempSpaceRect.width = 1; + tempSpaceRect.height = r.height; + + var sideMovedIn = 0; + for (i = 0; i < r.width; i++) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.left++; + sideMovedIn++; + } + } + if (ret.left < baseBounds.left - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.width - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.right--; + } + } + if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + sideMovedIn = 0; + tempSpaceRect.width = r.width; + tempSpaceRect.height = 1; + tempSpaceRect.x = 0; + for (i = 0; i < r.height; i++) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.top++; + sideMovedIn++; + } + } + if (ret.top < baseBounds.top - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.height - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.bottom--; + } + } + if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + } + return ret; + } + + public static function TransformAABBRect(r:Rectangle, m:Matrix) + { + var o1X = r.left; + var o1Y = r.top; + + var o2X = r.right; + var o2Y = r.top; + + var o3X = r.left; + var o3Y = r.bottom; + + var o4X = r.right; + var o4Y = r.bottom; + + var n1X = o1X * m.a + o1Y * m.c + m.tx; + var n1Y = o1X * m.b + o1Y * m.d + m.ty; + + var n2X = o2X * m.a + o2Y * m.c + m.tx; + var n2Y = o2X * m.b + o2Y * m.d + m.ty; + + var n3X = o3X * m.a + o3Y * m.c + m.tx; + var n3Y = o3X * m.b + o3Y * m.d + m.ty; + + var n4X = o4X * m.a + o4Y * m.c + m.tx; + var n4Y = o4X * m.b + o4Y * m.d + m.ty; + + r.left = Math.min(n1X, n2X, n3X, n4X); + r.right = Math.max(n1X, n2X, n3X, n4X); + + r.top = Math.min(n1Y, n2Y, n3Y, n4Y); + r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); + } + } +} diff --git a/job.py b/job.py index 989c991..77c09e8 100644 --- a/job.py +++ b/job.py @@ -3,6 +3,7 @@ import json from validate import * from args import * +import copy asset_src_schema = { "type":"object", @@ -69,19 +70,24 @@ base_path = os.path.join(self.out_dir, self.rel_path) if not os.path.exists(base_path): os.makedirs(base_path) + resource_names = [] for i,r in enumerate(resources): - path = os.path.join(base_path, "%s_%04d.png" % (self.name, i)) + resource_name = "%s_%04d.png" % (self.name, i) if len(resources) > 1 else self.name + ".png" + resource_names.append(resource_name) + path = os.path.join(base_path, resource_name) with open(path, "wb") as f: f.write(base64.b64decode(r)) if len(data) == 1: graphic_and_asset = {} (name, graphic_data) = data.items()[0] - graphic_and_asset = {"data":graphic_data} + graphic_and_asset = {"data":graphic_data, "resources":resource_names} with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps(graphic_and_asset)) else: + write_data = copy.deepcopy(data) + write_data["resources"] = resource_names with open(os.path.join(base_path, self.name + ".asset"), "w") as f: - f.write(pretty_dumps(data)) + f.write(pretty_dumps(write_data)) for name,details in data.iteritems(): with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps({"data":self.name + ".asset"})) diff --git a/old/Checkbox.as b/old/Checkbox.as deleted file mode 100644 index c5aaba2..0000000 --- a/old/Checkbox.as +++ /dev/null @@ -1,42 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - - public class Checkbox extends MovieClip - { - public var Enabled:Boolean = true; - public function Checkbox() - { - checkbox.gotoAndStop(1); - checkbox.addEventListener(MouseEvent.CLICK, Clicked); - } - - protected function Clicked(event) - { - if (!Enabled) return; - Toggle(); - if (OnClick != null) OnClick(OnClickParam); - } - - protected var checked = false; - public function set Checked(value) { checked = value; checkbox.gotoAndStop(checked ? 2 : 1); } - public function get Checked() { return checked; } - - public function set Text(value) { text.text = value; } - - public var OnClickParam; - public var OnClick; - - - public function Toggle() - { - checked = !checked; - checkbox.gotoAndStop(checked ? 2 : 1); - - - } - - } - -} diff --git a/old/GraphicExport-app.xml b/old/GraphicExport-app.xml deleted file mode 100644 index 5144634..0000000 --- a/old/GraphicExport-app.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - GraphicExport - 1.0 - GraphicExport - - GraphicExport - - - GraphicExport.swf - standard - false - true - false - portrait - auto - true - true - true - - - false - false - desktop extendedDesktop diff --git a/old/GraphicExport.exe b/old/GraphicExport.exe deleted file mode 100644 index 56315aa..0000000 --- a/old/GraphicExport.exe +++ /dev/null Binary files differ diff --git a/old/GraphicExport.fla b/old/GraphicExport.fla deleted file mode 100644 index 0b78ed7..0000000 --- a/old/GraphicExport.fla +++ /dev/null Binary files differ diff --git a/old/GraphicExport.swf b/old/GraphicExport.swf deleted file mode 100644 index 542db97..0000000 --- a/old/GraphicExport.swf +++ /dev/null Binary files differ diff --git a/old/NewGraphicDialog.as b/old/NewGraphicDialog.as deleted file mode 100644 index 152011c..0000000 --- a/old/NewGraphicDialog.as +++ /dev/null @@ -1,224 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - import flash.events.*; - import flash.filesystem.File; - import flash.net.FileFilter; - import Defs.GraphicDef; - import flash.text.engine.GraphicElement; - - public class NewGraphicDialog extends MovieClip - { - - public function NewGraphicDialog() - { - // constructor code - Init(); - } - - var typeButtons:Array = new Array(); - - public function Init() - { - graphicPath.text = "Path to Graphic Here"; - - this.removeChild(browseButton); - - var newBrowseButton = new UI_GenericBlueButton(); - newBrowseButton.Text = "Browse"; - newBrowseButton.OnClick = BrowseForFile; - newBrowseButton.x = browseButton.x + (newBrowseButton.width / 2); - newBrowseButton.y = browseButton.y + (newBrowseButton.height / 2); - addChild(newBrowseButton); - - var newTestButton = new UI_GenericBlueButton(); - newTestButton.Text = "Export"; - newTestButton.OnClick = TestFile; - newTestButton.x = testButton.x + (newTestButton.width / 2); - newTestButton.y = testButton.y + (newTestButton.height / 2); - addChild(newTestButton); - - this.removeChild(typePlaceholderButton); - - var typeX = typePlaceholderButton.x; - var typeY = typePlaceholderButton.y + (typePlaceholderButton.height / 2); - - - var typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Graphic (1)"; - typeButton.OnClick = function(){ SetType(1); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Skeletal (3)"; - typeButton.OnClick = function(){ SetType(3); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Scene (6)"; - typeButton.OnClick = function(){ SetType(6); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - animationCheckbox.Checked = true; - //browseButton - //typePlaceholderButton - //usesInput - //usesText.text = "" - } - - var usesInputDefaultText = "Comma Seperated List of Uses Here"; - - public static var fakeID = 9999999; - public function TestFile() - { - fakeID++; - var graphicName = graphicPath.text; - var graphicData = {id:fakeID,graphic:graphicPath.text,v:1,fs:0,p:0,type:selectedType}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new GraphicDef(graphicData); - - this.Hide(); - graphicExport.ExportItem(graphicDef); - } - - var selectedType = 1; - public function SetType(type:Number) - { - selectedType = type; - - for(var i = 0; i < typeButtons.length; i++) - { - typeButtons[i].Enabled = true; - } - - animationCheckbox.visible = false; - - switch(type) - { - case 1: { - typeButtons[0].Enabled = false; - animationCheckbox.visible = true; - break; - } - case 3: typeButtons[1].Enabled = false; break; - case 6: typeButtons[2].Enabled = false; break; - } - } - - var graphicExport:GraphicExport; - public function Show(parentClip) - { - this.graphicExport = parentClip; - - parentClip.addChild(this); - - SetType(selectedType); - - var graphicList = GameData.Instance().GraphicDefines; - - var usesString:String = ""; - var uniqueUseTypes:Array = new Array(); - for (var i = 0; i < graphicList.length; i++) - { - var graphicDef:GraphicDef = graphicList[i]; - var uses = graphicDef.ExportParams['uses']; - for (var usage in uses) - { - if (uniqueUseTypes[uses[usage]] == null) - { - uniqueUseTypes[uses[usage]] = uses[usage]; - usesString += uses[usage] + ", "; - } - } - } - - graphicPath.text = ""; - - } - - public function CloseClicked(event) - { - Hide(); - } - - public function Hide() - { - if (this.parent != null) this.parent.removeChild(this); - } - - public function BrowseForFile() - { - var file:File = new File(); - var swfTypeFilter:FileFilter = new FileFilter("SWF Files","*.swf"); - file.addEventListener(Event.SELECT, openFile); - file.browse([swfTypeFilter]); - } - - private function openFile(event:Event):void - { - _strace(event.target.nativePath); - var path:String = event.target.nativePath; - var pathParts:Array = path.split("Graphics\\"); - if (pathParts.length == 2) - { - var fileRemainder:String = pathParts[1]; - var withoutExtension:String = fileRemainder.split(".")[0]; - var pattern:RegExp = /\\/g; - withoutExtension = withoutExtension.replace(pattern, "/"); - _strace(withoutExtension); - graphicPath.text = withoutExtension; - - if (withoutExtension.indexOf("Backgrounds") > -1) - { - SetType(6); - } - - if (withoutExtension.indexOf("Monsters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Characters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Portraits") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Quest") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Equipment") > -1) - { - SetType(1); - } - - - } - } - - - } - -} diff --git a/old/PNGExportHelper.as b/old/PNGExportHelper.as deleted file mode 100644 index f8c4c9d..0000000 --- a/old/PNGExportHelper.as +++ /dev/null @@ -1,253 +0,0 @@ -package -{ - import flash.display.*; - import com.adobe.images.*; - import flash.utils.*; - import flash.net.*; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import flash.geom.Point; - - public class PNGExportHelper - { - public static var UseExpandedBitmaps = false; - public static var AlphaThreshold = 5; - - private static function ExpandBitmapBorders(bd:BitmapData, bgColor = 0x0, passes = 1):BitmapData - { - /* - var thresh:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - thresh.threshold(bd, bd.rect, new Point(), "<", (20 << 24), bgColor, 0xFF000000, true); - */ - var sampled:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - bd.lock(); - sampled.lock(); - - for (var y = 0; y < bd.height; y++) - { - for (var x = 0; x < bd.width; x++) - { - var oldVal:uint = bd.getPixel32(x, y); - var a:uint = (oldVal & 0xFF000000) >>> 24; - var rgb:uint = (oldVal & 0xFFFFFF); - if (a > AlphaThreshold) - { - sampled.setPixel32(x, y, (0xFF << 24) | rgb); - } - else - { - sampled.setPixel32(x, y, bgColor); - } - } - } - sampled.unlock(); - bd.unlock(); - - return ExpandBitmapBordersInternal(sampled, bgColor, passes); - } - - private static function ExpandBitmapBordersInternal(bd:BitmapData, bgColor, passes):BitmapData - { - var output:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - - var scale = 16; - var scaled:BitmapData = new BitmapData(bd.width/scale, bd.height/scale, true, bgColor); - var mat:Matrix = new Matrix(); - mat.scale(1/scale, 1/scale); - scaled.draw(bd, mat, null, null, null, true); - - output.lock(); - - var colors:Array = new Array(); - var weights:Array = new Array(); - - for (var oy = 0; oy < scaled.height; oy++) - { - - for (var ox = 0; ox < scaled.width; ox++) - { - - var scaledVal:uint = scaled.getPixel32(ox, oy); - var scaleda:uint = (scaledVal & 0xFF000000) >>> 24; - if (scaleda == 0 || scaleda == 255) - { - output.copyPixels(bd, new Rectangle(ox * scale, oy * scale, scale, scale), new Point(ox * scale, oy * scale)); - continue; - } else { - //_strace(scaleda+""); - } - - - for (var y = oy * scale; y < oy * scale + scale; y++) - { - for (var x = ox * scale; x < ox * scale + scale; x++) - { - var oldVal:uint = bd.getPixel32(x, y); - var a:uint = (oldVal & 0xFF000000) >>> 24; - var rgb:uint = (oldVal & 0xFFFFFF); - - if (a == 0 && rgb == bgColor) - { - colors.length = 0; - weights.length = 0; - - for (var y1 = y - 2; y1 <= y + 2; y1++) - { - for (var x1 = x - 2; x1 <= x + 2; x1++) - { - var dist = Math.abs(x1 - x) + Math.abs(y1 - y); - if (dist >= 3) continue; - - if (x1 >= 0 && x1 < bd.width && y1 >= 0 && y1 < bd.height) - { - colors.push(bd.getPixel(x1, y1)); - weights.push(1 - dist * 0.2); - } - } - } - - var newVal = AveragePixels(colors, weights, bgColor); - if (newVal == null) - { - newVal = oldVal; - } - else - { - var newR:uint = (newVal & 0xFF0000) >> 16; - var newG:uint = (newVal & 0xFF00) >> 8; - var newB:uint = (newVal & 0xFF); - - if (newVal != 0 && colors.length >= 4) - { - var bp = true; - } - - var sorted = colors.sort(function(a, b) - { - var aR:uint = (a & 0xFF0000) >> 16; - var aG:uint = (a & 0xFF00) >> 8; - var aB:uint = (a & 0xFF); - - var bR:uint = (b & 0xFF0000) >> 16; - var bG:uint = (b & 0xFF00) >> 8; - var bB:uint = (b & 0xFF); - - var diffA = Math.abs(aR - newR) + Math.abs(aG - newG) + Math.abs(aB - newB); - var diffB = Math.abs(bR - newR) + Math.abs(bG - newG) + Math.abs(bB - newB); - - return diffA - diffB; - - }, Array.RETURNINDEXEDARRAY | Array.DESCENDING); - - var toRemove = Math.min(2, colors.length - 4); - var removed = 0; - for (var i = 0; i < colors.length; i++) - { - var index = sorted.indexOf(i + removed); - if (index < toRemove) - { - colors.splice(i, 1); - weights.splice(i, 1); - removed++; - i--; - if (removed == toRemove) break; - } - } - - var fixOutliersVal = AveragePixels(colors, weights, bgColor); - if (fixOutliersVal == null) newVal = (0xFF << 24) | newVal; - - newVal = (0xFF << 24) | fixOutliersVal; - } - - output.setPixel32(x, y, newVal); - } - else - { - output.setPixel32(x, y, oldVal); - } - } - } - }//end outer scaled x - }//End outer scaled y - - bd.unlock(); - output.unlock(); - - passes--; - if (passes > 0) - { - return ExpandBitmapBordersInternal(output, bgColor, passes); - } - else - { - return output; - } - } - - private static function AveragePixels(colors:Array, weights:Array, bgColor:uint):uint - { - var rTotal = 0; - var gTotal = 0; - var bTotal = 0; - - var wTotal = 0; - - for (var i = 0; i < colors.length; i++) - { - var color:uint = colors[i]; - var a:uint = (color & 0xFF000000) >>> 24; - var rgb:uint = (color & 0xFFFFFF); - - if (a == 0 && rgb == bgColor) - { - colors.splice(i, 1); - weights.splice(i, 1); - i--; - continue; - } - - var r:uint = (rgb & 0xFF0000) >>> 16; - var g:uint = (rgb & 0xFF00) >>> 8; - var b:uint = (rgb & 0xFF); - var w = weights[i]; - - rTotal += w * r; - gTotal += w * g; - bTotal += w * b; - - wTotal += w; - } - - if (wTotal == 0) - { - return null; - } - - rTotal /= wTotal; - gTotal /= wTotal; - bTotal /= wTotal; - - var rFinal = Math.max(0, Math.min(255, Math.round(rTotal))); - var gFinal = Math.max(0, Math.min(255, Math.round(gTotal))); - var bFinal = Math.max(0, Math.min(255, Math.round(bTotal))); - - return (uint(rFinal) << 16) | (uint(gFinal) << 8) | (uint(bFinal)); - } - - - - public static function GetExportPNG(bd:BitmapData):ByteArray - { - if (!UseExpandedBitmaps) return PNGEncoder.encode(bd); - - var expanded:BitmapData = ExpandBitmapBorders(bd, 0x0, 2); - - //var fr:FileReference = new FileReference(); - //fr.save(PNGEncoder.encode(expanded), "output.png"); - - return PNGEncoderWithAlpha.encode(expanded, bd); - } - - } -} \ No newline at end of file diff --git a/old/PreviewHolder.as b/old/PreviewHolder.as deleted file mode 100644 index 587bf68..0000000 --- a/old/PreviewHolder.as +++ /dev/null @@ -1,57 +0,0 @@ -package { - import flash.display.MovieClip; - - public class PreviewHolder extends MovieClip - { - - var startingWidth = 1024; - var startingHeight = 1024; - - public function PreviewHolder() - { - startingWidth = this.width; - startingHeight = this.height; - } - - var clips:Array = new Array(); - public function AddClip(clip) - { - clips.push(clip); - this.addChild(clip); - ArrangeClips(); - } - - public function ArrangeClips() - { - var numCols = Math.ceil(Math.sqrt(clips.length)); - var maxY = 0; - var maxX = 0; - var clipIndex = 0; - for (var row = 0; row < numCols; row++) - { - var clipX = 0; - var clipY = maxY; - for (var col = 0; col < numCols; col++) - { - if (clipIndex == clips.length) break; - clips[clipIndex].x = clipX; - clips[clipIndex].y = clipY; - clipX += clips[clipIndex].width; - var clipBottom = clips[clipIndex].y + clips[clipIndex].height; - if (clipBottom > maxY) maxY = clipBottom; - - var clipRight = clips[clipIndex].x + clips[clipIndex].width; - if (clipRight > maxX) maxX = clipRight; - clipIndex++; - } - } - - var scale = Math.min(startingWidth / maxX, startingHeight / maxY); - if (scale > 1) scale = 1; - - this.scaleX = this.scaleY = scale; - } - - } - -} diff --git a/old/Utils.as b/old/Utils.as deleted file mode 100755 index 02b4f12..0000000 --- a/old/Utils.as +++ /dev/null @@ -1,1202 +0,0 @@ -package old -{ - /* This class has functions similar to the Utils.as in the /flash/Dialogs folder. However, some of - * those functions are different here than in /flash/Dialogs/Utils.as for... reasons? flash folder reasons! - */ - import flash.utils.*; - import flash.net.*; - import flash.display.*; - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.geom.Point; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import flash.geom.ColorTransform; - import fl.motion.Color; - import fl.transitions.Tween; - import fl.transitions.easing.*; - import fl.transitions.TweenEvent; - import flash.net.navigateToURL; - import flash.external.ExternalInterface; - import flash.system.Capabilities; - import flash.filters.*; - import flash.filters.ColorMatrixFilter; - import com.adobe.images.JPGEncoder; - import flash.globalization.DateTimeFormatter; - - import djarts.utils.Base64; - import djarts.utils.PNGEnc; - import User.UserOptions; - - public class Utils - { - //["K","M","B","T","q", "Q", "s", "S","O","N","d","U","D","!","@","#","$","%","^","&","*"] - static var symbols = ["K","M","B","t","q", "Q", "s", "S","o","n","d","U","D","T","Qt","Qd","Sd","St","O","N","v","c"]; - static var divisors = []; - - public static function FormatBigNumber(number:*, round:Boolean=false):String - { - if (number < 0) return '-' + FormatBigNumber(Math.abs(number), round); - - var isWholeNumber = (Math.floor(number) == number); - round = round || isWholeNumber; - - if (number < 1000) - { - if (round) - { - return Math.round(number).toString(); - } - else - { - var decimalPlaces = (number >= 100) ? 1 : 2; // Below 100, show two decimal places. Above, only one. - var roundMult = Math.pow(10, decimalPlaces); - var rounded = Math.round(number); - var bigRounded = Math.round(number * roundMult); - var roundedDifferenceProportion = Math.abs(bigRounded / roundMult - rounded) / rounded; - - if (roundedDifferenceProportion < 0.001) - { - // Not a whole number, but the decimal places aren't worth showing - // Below also handles this, but is slower - return rounded.toString(); - } - else - { - var str:String = bigRounded.toString(); - str = str.substr(0, str.length - decimalPlaces) + "." + str.substr(str.length - decimalPlaces); - - while (str.charAt(str.length - 1) == "0") str = str.substr(0, str.length - 1); //should only ever happen once - if (str.charAt(str.length - 1) == ".") str = str.substr(0, str.length - 1); //probably won't happen at all - - return str; - } - } - } - - // Determine which symbol to use - var power = Math.floor(Math.log(number) / Math.log(1000)); - var index = Math.min(power-1, symbols.length-1); - var amount = number / Math.pow(1000, index+1); - var symbol = (index >= 0 && index < symbols.length) ? symbols[index] : ""; - - // If it's too big for a symbol (or if we just WANT to) - if (amount >= 1000 || UserOptions.ForceScientific) - { - // scientific notation - var power = Math.floor(Math.log(number) / Math.log(10)); - var num = number / Math.pow(10, power); - if (num == 10) { - num = 1; - power += 1; - } - var numString = "" + num; - numString = numString.substr(0, Math.min(4, numString.length)); - return numString + "e" + power; - - } - else - { - // Format with the symbol - // determine number of whole digits (will dictate how many decimals we show) - var whole = Math.floor(amount); - var amount_str:String = String(whole); - - var decimalDivider = 100/Math.pow(10,amount_str.length-1); - - //round to nearest decimal place - amount = int(amount*decimalDivider)/decimalDivider; - - var amountString:String = amount.toString(); - - var noDecimal:String = amountString.replace(".",""); - if (noDecimal.length == 2) - { - if (amountString.indexOf(".") != -1) amountString += "0"; - else amountString += ".0"; - } - else if (noDecimal.length == 1) amountString += ".00"; - - return amountString+symbol; // concat symbol - } - } - - private static var BigNumberRegex = new RegExp(/(\d*),?(\d*)(.*)/); - // Note-DG: This is mostly just used for definitions in the database, that don't require precision. - // This way we can define values in the database as 100B instead of 100000000000. - public static function ParseBigNumberString(number:String):Number - { - var regexArray:Array = BigNumberRegex.exec(number); - var magnitude = symbols.indexOf(regexArray[3]); - var thousands:Number; - if (regexArray[1]) { - thousands = regexArray[1]; - if (regexArray[2]) { // if numbers are split by comma, multiply by 1000 - thousands *= 1000; - } - } else { - thousands = 0; - } - var hundreds:Number = regexArray[2] ? regexArray[2] : 0; - - return (thousands + hundreds) * Math.pow(1000, magnitude + 1); - } - - public static function ParseNumberRange(range:String):Array - { - var split:Array = range.split(','); - return [Number(split[0]), Number(split[1])]; - } - - public static function DesaturateFilter() - { - var desatMatrix:Array = []; - var cmFilter; - - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // red - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // green - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // blue - desatMatrix = desatMatrix.concat([0, 0, 0, 1, 0]); // alpha - cmFilter = new ColorMatrixFilter(desatMatrix); - - return cmFilter; - } - - public static function GetUserAgent():String - { - try - { - var userAgent = ExternalInterface.call("window.navigator.userAgent.toString"); - var browser:String = "[Unknown Browser]"; - - if (userAgent.indexOf("Safari") != -1) - { - browser = "Safari"; - } - if (userAgent.indexOf("Firefox") != -1) - { - browser = "Firefox"; - } - if (userAgent.indexOf("Chrome") != -1) - { - browser = "Chrome"; - } - if (userAgent.indexOf("MSIE") != -1) - { - browser = "Internet Explorer"; - } - if (userAgent.indexOf("Opera") != -1) - { - browser = "Opera"; - } - } - catch (e:Error) - { - //could not access ExternalInterface in containing page - return "[No ExternalInterface]"; - } - - return browser; - } - - public static function GetScreenshot(stage:Stage):String { - var scale:Number = 0.25; - var result:String = null; - var blurFilter:BlurFilter = new BlurFilter(3, 3, BitmapFilterQuality.HIGH); - - var bData:BitmapData = new BitmapData(stage.stageWidth * scale, - stage.stageHeight * scale, false, 0x348400); - var matrix:Matrix = new Matrix(); - matrix.scale(scale, scale); - - bData.draw(stage, matrix); - bData.applyFilter(bData, bData.rect, new Point(0, 0), blurFilter); - - - var imgBytes:ByteArray = new JPGEncoder(80).encode(bData); - //var imgBytes:ByteArray = PNGEnc.encode(bData); - if (imgBytes) { - var screenshotBase64:String = Base64.encode(imgBytes); - if (screenshotBase64) { - result = screenshotBase64; - } - } - - return result; - } - - public static function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function PlayerVersion() - { - - // Get the player's version by using the getVersion() global function. - var versionNumber:String = Capabilities.version; - - // The version number is a list of items divided by "," - var versionArray:Array = versionNumber.split(","); - var length:Number = versionArray.length; - //for(var i:Number = 0; i < length; i++) _strace("versionArray["+i+"]: "+versionArray[i]); - - // The main version contains the OS type too so we split it in two - // and we'll have the OS type and the major version number separately. - var platformAndVersion:Array = versionArray[0].split(" "); - //for(var j:Number = 0; j < 2; j++) _strace("platformAndVersion["+j+"]: "+platformAndVersion[j]); - //_strace("-----"); - - var majorVersion:Number = parseInt(platformAndVersion[1]); - var minorVersion:Number = parseInt(versionArray[1]); - var buildNumber:Number = parseInt(versionArray[2]); - - return Number(majorVersion+"."+minorVersion); - } - - - public static function OpenLocalURLTop(url) - { - navigateToURL(new URLRequest(GameSettings.Approot+url), "_top" ); - } - - public static function OpenLocalURL(url) - { - navigateToURL(new URLRequest(GameSettings.Approot+url), "_blank" ); - } - - public static function OpenURL(url, window = "_blank") - { - navigateToURL(new URLRequest(url), window); - } - - public static var ExitFullScreenCallback; - - public static function WallPublish(title:String, desc1:String, desc2:String, image:String, url = null, action = null) - { - if (Utils.ExitFullScreenCallback) Utils.ExitFullScreenCallback(); - //_strace(title + "\n" + desc1 + "\n" + desc2 + "\n" + image + "\n"); - ExternalInterface.call("askToPublish", title, url, desc1, desc2, image, action); - - //if (Settings.Platform == Settings.HI5) { - //DialogManager.Instance().ShowMessageBox("The message was posted to your wall!", "", "OK", null); - //} - } - - public static function SendToRecipients(recipients:Array, description, data) - { - if (!GameSettings.IsFacebook) return; - - if (Utils.ExitFullScreenCallback) Utils.ExitFullScreenCallback(); - try { - ExternalInterface.call("sendToRecipients", recipients, description ,data); - } - catch (e) - { - _strace(e.message); - } - } - - - public static function GetFriendData() - { - try { - return ExternalInterface.call("pollInviteData"); - } - catch (e) - { - _strace(e.message); - } - } - - - public static function singleBounceEase(t:Number, b:Number, c:Number, d:Number):Number - { - t = t / d; - if (t < 0.7) { - t *= 1.0 / 0.65; - return c * (t * t) + b; - } - return c * (t * t) + b; - } - - public static function Finish(e:TweenEvent) - { - //_strace("done " + e.currentTarget.obj.x + " " + e.currentTarget.obj.y + " " + e.currentTarget.obj.scaleX + " " + e.currentTarget.obj.scaleY); - e.currentTarget.removeEventListener(TweenEvent.MOTION_FINISH, Finish); - } - public static function Popup(mc, startScale = 0.8, finishCallback = null) - { - var rect:Rectangle = mc.getRect(mc); - var targetX = mc.x; - var targetY = mc.y; - var centerX = mc.x + rect.left + mc.width / 2.0; - var centerY = mc.y + rect.top + mc.height / 2.0; - var startX = centerX - (rect.left + mc.width / 2.0) * startScale; - var startY = centerY - (rect.top + mc.height / 2.0) * startScale; - var tweenSX = new Tween(mc, "scaleX", singleBounceEase, startScale, 1.0, 4, false); - if (finishCallback) tweenSX.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenSY = new Tween(mc, "scaleY", singleBounceEase, startScale, 1.0, 4, false); - if (finishCallback) tweenSY.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenX = new Tween(mc, "x", singleBounceEase, startX, targetX, 4, false); - if (finishCallback) tweenX.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenY = new Tween(mc, "y", singleBounceEase, startY, targetY, 4, false); - if (finishCallback) tweenY.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - return [tweenSX, tweenSY, tweenX, tweenY]; - } - public static function StringSplit(s:String, delim:String, max:int = -1):Array - { - var ret:Array = s.split(delim); - if (max != -1) { - var more:String = ret.slice(max - 1).join(delim); - ret.splice(max - 1); - ret[max - 1] = more; - } - return ret; - } - - public static function StringStartsWith(str:String, substr:String):Boolean - { - if (substr.length > str.length) return false; - return (str.substr(0, substr.length) == substr); - } - - public static function StringEndsWith(str:String, substr:String):Boolean - { - if (substr.length > str.length) return false; - return (str.substr(str.length - substr.length, substr.length) == substr); - } - - public static function StringContains(str:String, substr:String):Boolean - { - return (str.indexOf(substr) !== -1); - } - - private static var vowelsAndH = { - "a":true, "A":true, - "e":true, "E":true, - "i":true, "I":true, - "o":true, "O":true, - "u":true, "U":true, - "h":true, "H":true - } - public static function StringStartsWithVowelOrH(s:String):Boolean - { - if (vowelsAndH[s.charAt(0)]) return true; - return false; - } - - public static function CopyObject(obj, except = null) - { - var i; - if (except == null) except = []; - if (obj is Array) { - var obj2 = []; - for (i = 0; i < obj.length; i++) { - obj2.push(Utils.CopyObject(obj[i])); - } - return obj2; - } - var ret:Object = {}; - for (i in obj) - { - if (except.indexOf(i) == -1) { - ret[i] = obj[i]; - } - } - - return ret; - } - public static function CopyToObject(objFrom, objTo, except = null) - { - if (except == null) except = []; - for (var i in objFrom) - { - if (except.indexOf(i) == -1) { - objTo[i] = objFrom[i]; - } - } - } - public static function CopyToObjectOnly(objFrom, objTo, only) - { - if (only == null) return; - for (var i in only) - { - if (objFrom.hasOwnProperty(only[i])) - { - objTo[only[i]] = objFrom[only[i]]; - } - } - } - - public static function ColorizeRGB(clip:MovieClip, r:int,g:int,b:int) - { - var cTransform = clip.transform.colorTransform; - cTransform.redOffset = r; - cTransform.greenOffset = g; - cTransform.blueOffset = b; - clip.transform.colorTransform = cTransform; - } - - public static function hex2rgb (hex):Object - { - var red = hex>>16; - var greenBlue = hex-(red<<16) - var green = greenBlue>>8; - var blue = greenBlue - (green << 8); - return({r:red, g:green, b:blue}); - } - - public static function RGBtoHEX(r, g, b) { - return r << 16 | g << 8 | b; - } - - /** - * NOTE: An alpha of 1 will make the object a solid color (good for silhouettes) - */ - public static function TintDisplayObject(obj:DisplayObject, color:uint = 0xffffff, alpha:Number = 1.0) - { - var cTint:Color = new Color(); - cTint.setTint(color, alpha); - obj.transform.colorTransform = cTint; - } - - // given an origin (ox, oy) and a look at point (tx, ty), - // and a clip with the given number of rotation states, which - // rotation should we pick? - public static function Rotation(ox, oy, tx, ty, rotations) - { - var delta:Point = new Point(tx - ox, ty - oy); - if (Point.distance(delta, new Point(0.0, 0.0)) < 0.00001) { - delta.y = -1.0; - } - var d = ( - (-Math.floor( - /* calculate the rotation and scale it */ - Math.atan2(delta.y, delta.x) / (Math.PI * 2.0) * rotations - + 0.5 // add 0.5 and take the floor (round to closest int) - ) - + rotations) // atan2 returns in the range -pi to pi, measured ccw from +x, - // we negate it and add rotations again to get it in the range - // [0, rotations] - % rotations) + 1; // add 1 to reference frames - return d; - } - /* performs multiple operations asynchronously, but wait for them all to finish: - * instead of calling a bunch of functions and passing callbacks, pass those callbacks to WaitForFunctions - * and use ret.callbacks[0], ret.callbacks[1], etc... as the callbacks - * this will wait until every command is complete and call all the callbacks at once. - * - * For instance, to load multiple graphics packs asynchronously and wait for them all to finish, - * call var ret = WaitForFunctions([DoneLoading, null, null, null]); to generate - * ret.callbacks[0]..ret.callbacks[3], and pass these to 4 calls to LoadExternalGraphics. - * When these 4 calls complete, the provided 4 functions will be called with the arguments returned - * from the callbacks (in this case, only DoneLoading will be called since the - * other callbacks are null). - */ - public static function WaitForFunctions(...funcs):Object - { - var ret:Object = {}; - // has a callback been hit? - ret.hit = new Array(funcs.length); - // what were the original arguments the callback was called with - ret.args = new Array(funcs.length); - // a list of the artifical callbacks we are providing - ret.callbacks = new Array(funcs.length); - // the real callbacks - ret.funcs = funcs; - ret.done = false; - - ret.immediate = []; - - for (var i = 0; i < funcs.length; i++) { - // we have to setup this temp callback in another function, because the anon function's - // activation object will contain the current scope, meaning that the variable - // i will be updated in each function; if we do it in a seperate function each - // activation object will reference a different i - ret.callbacks[i] = Utils.SetupFunction(ret, i); - } - return ret; - } - - /** - * Returns the standard money format for an integer amount - */ - public static function FormatCurrency(amount:int, symbol:String = "$"):String - { - var afterDecimal:String = (amount % 100).toString(); - while (afterDecimal.length < 2) afterDecimal = "0" + afterDecimal; //mmmm string concatenation - - var beforeDecimal:String; - if (amount > 100) - { - beforeDecimal = Math.floor(amount/100).toString(); - } - else - { - beforeDecimal = "0"; - } - - return symbol + beforeDecimal + "." + afterDecimal; - } - - public static function FormatNumber(amount){ - var whole = Math.floor(amount); - // convert the number to a string - var amount_str:String = String(whole); - var total_str:String = String(amount); - - var number_array:Array = []; - var start:Number; - var end:Number = amount_str.length; - while (end > 0) { - start = Math.max(end - 3, 0); - number_array.unshift(amount_str.slice(start, end)); - end = start; - } - - var point = total_str.indexOf("."); - - var ret = number_array.join(","); - if (point != -1 && point < total_str.length) - { - ret += total_str.substr(point); - } - - return ret; - } - - protected static function SetupFunction(ret, i):Function - { - var a:Function = - function(...rest) { - if (ret.immediate[i]) ret.immediate[i].apply(null, rest); - ret.hit[i] = true; - ret.args[i] = rest; - var ok:Boolean = true; - var j; - for (j = 0; j < ret.hit.length; j++) { - if (!ret.hit[j]) { ok = false; break; } - } - if (ok && !ret.done) { - ret.done = true; - for (j = 0; j < ret.funcs.length; j++) { - if (ret.funcs[j] != null) ret.funcs[j].apply(null, ret.args[j]); - } - } - }; - return a; - } - - // useful for the paned dialogs to show a certain pane/button - public static function OnlyVisible(obj, set:Array, index:int) - { - for (var i in set) { - if (i != index) { - obj[set[i]].visible = false; - } else { - obj[set[i]].visible = true; - } - } - } - public static function AllVisible(obj, set:Array) - { - for (var i in set) { - obj[set[i]].visible = true; - } - } - // set one of a list of tabs to be enabled - public static function OnlyToggled(obj, set:Array, index:int) - { - for (var i in set) { - if (i != index) { - obj[set[i]].SetToggled(false); - } else { - obj[set[i]].SetToggled(true); - } - } - } - // get the frame number of a label in the timeline - public static function GetLabelFrame(mc, name:String):int - { - for (var l in mc.currentLabels) { - if (mc.currentLabels[l].name == name) return mc.currentLabels[l].frame; - } - return 1; - } - // generate a quick text field of a certain color/style - public static function BasicTextField(color:uint, - size:int, - font:String, - text:String, - additional:Object = null, - align = "left"):TextField - { - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.align = align; - if (additional != null) for (var a in additional) f[a] = additional[a]; - f.font = font; - f.color = color; - f.size = size; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.text = text; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - return t; - } - public static function var_dump(_obj, name = "Dump") - { - _strace(name + " " + (_obj) + " {"); - flash.utils.describeType(_obj); - var varList:XMLList = flash.utils.describeType(_obj)..variable; - - for(var i:int; i < varList.length(); i++) - { - //Show the name and the value - _strace(" " + varList[i].@name+' = '+ _obj[varList[i].@name]); - } - _strace("}"); - } - - public static function SetChildFrames(parentClip, frame, exclude = null) - { - if (parentClip is MovieClip && parentClip.name != exclude) - { - parentClip.gotoAndStop(frame); - for (var i = 0; i < parentClip.numChildren; i++) - { - Utils.SetChildFrames(parentClip.getChildAt(i), frame, exclude); - } - } - } - - public static function SetChildFramesNoParent(parentClip, frame, exclude = null) - { - if (parentClip is MovieClip && parentClip.name != exclude) - { - for (var i = 0; i < parentClip.numChildren; i++) - { - Utils.SetChildFrames(parentClip.getChildAt(i), frame, exclude); - } - } - } - - //modifies the array passed as parameter, following the MO of the built in Array.sort() - public static function insertionSort(array:Array, compareFunction:Function):void - { - for(var i:int=1; i < array.length; i++) - { - var value:Object = array[i]; - var k:int=i-1; - while( k >= 0 && compareFunction(array[k], value) == -1) - { - array[k+1]=array[k]; - k--; - } - array[k+1]=value; - } - } - - - public static function Screenshot(sourceClip, receiverURL, filename) - { - - var jpgSource:BitmapData; - - if (sourceClip is Stage) - { - jpgSource = new BitmapData (sourceClip.stageWidth, sourceClip.stageHeight); - } else { - jpgSource = new BitmapData (sourceClip.width, sourceClip.height); - } - - jpgSource.draw(sourceClip); - - var jpgEncoder:JPGEncoder = new JPGEncoder(85); - var jpgStream:ByteArray = jpgEncoder.encode(jpgSource); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - var jpgURLRequest:URLRequest = new URLRequest(receiverURL+"?name="+filename); - jpgURLRequest.requestHeaders.push(header); - jpgURLRequest.method = URLRequestMethod.POST; - jpgURLRequest.data = jpgStream; - navigateToURL(jpgURLRequest, "_blank"); - - } - - - public static function SetColors(clip, color) - { - var colorTransform:ColorTransform; - - if (clip == null || color == null) return; - - if (clip.hasOwnProperty("outline") && clip.outline != null) - { - colorTransform = clip.outline.transform.colorTransform; - colorTransform.color = color.Outline; - clip.outline.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryOutline") && clip.secondaryOutline != null) - { - colorTransform = clip.secondaryOutline.transform.colorTransform; - colorTransform.color = color.LightOutline; - clip.secondaryOutline.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("color") && clip.color != null) - { - colorTransform = clip.color.transform.colorTransform; - colorTransform.color = color.Primary; - clip.color.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryColor") && clip.secondaryColor != null) - { - colorTransform = clip.secondaryColor.transform.colorTransform; - colorTransform.color = color.Secondary; - clip.secondaryColor.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("shadow") && clip.shadow != null) - { - colorTransform = clip.shadow.transform.colorTransform; - colorTransform.color = color.Shadow; - clip.shadow.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryShadow") && clip.secondaryShadow != null) - { - colorTransform = clip.secondaryShadow.transform.colorTransform; - colorTransform.color = color.SecondaryShadow; - clip.secondaryShadow.transform.colorTransform = colorTransform; - } - } - /* returns a rect with the x, and y pos to center and the scaleX and scaleY as width and height */ - public static function GetUniformScaleRect(clip:MovieClip, maxWidth, maxHeight) - { - var rect:Rectangle = new Rectangle(0,0,0,0); - - var widthScale = Math.min(maxWidth / clip.width, 999); - var heightScale = Math.min(maxHeight / clip.height, 999); - - var scale = 1; - if (widthScale > heightScale) - { - scale = heightScale; - } else { - scale = widthScale; - } - - rect.width = clip.width * scale; - rect.height = clip.height * scale; - - var pb = clip.getBounds(clip); - var xadjust = -pb.left * scale; - var yadjust = -pb.top * scale; - - rect.x = xadjust + (maxWidth - rect.width) / 2; - rect.y = yadjust + (maxHeight - rect.height) / 2; - - rect.width = scale; - rect.height = scale; - - return rect; - } - - public static function Dec2Hex(d) - { - var chars:String = "0123456789ABCDEF"; - var str:String = ""; - while (d > 0 || str.length < 2) - { - var digit = d % 16; - d = (d - digit) / 16; - str = chars.charAt(digit) + str; - } - return str; - } - - public static function Hex2Dec(h:String) - { - var chars:String = "0123456789ABCDEF"; - var val = 1; - var res = 0; - for (var i = h.length - 1; i >= 0; i--) - { - res += chars.indexOf(h.substr(i, 1)) * val; - val *= 16; - } - return res; - } - - public static function ShallowCopyArray(array:Array) - { - if (!array) return null; - - var newArray:Array = []; - for (var i:int = 0; i < array.length; i++) - { - newArray.push(array[i]); - } - return newArray; - } - - /* Note: Will fail if any items in either array have reference type semantics (unless they point to the same object) - * (as opposed to value type semantics) - */ - public static function areEqual(a:Array,b:Array):Boolean { - if(a.length != b.length) { - return false; - } - var len:int = a.length; - for(var i:int = 0; i < len; i++) { - if(a[i] !== b[i]) { - return false; - } - } - return true; - } - - /* Note: Will fail if any items in either array have reference type semantics - * (as opposed to value type semantics) - */ - public static function objectsAreEqual(a:Object,b:Object):Boolean { - - for (var i in a) - { - if (!b.hasOwnProperty(i) || a[i] != b[i]) return false; - } - - return true; - } - - public static function DeepCopyClone (source : Object) : * - { - var array : ByteArray = new ByteArray (); - - array.writeObject (source); - array.position = 0; - - return array.readObject (); - } - - // {a:1, b:2} => [1,2] - public static function ObjectValues (obj:Object):Array { - var array = []; - for (var key in obj) array.push(obj[key]); - return array; - } - - // {a:1, b:2} => ["a","b"] - public static function ObjectKeys (obj:Object):Array { - var array = []; - for (var key in obj) array.push(key); - return array; - } - - // normal random variate generator; mean m, standard deviation s - public static function BoxMullerRandomNormal(m:Number, s:Number) : Number - { - var x1, x2, w, y1:Number; - var y2:Number; - var use_last:Boolean = false; - - if (use_last == true) /* use value from previous call */ - { - y1 = y2; - use_last = false; - } - else - { - do { - x1 = 2.0 * Math.random() - 1.0; - x2 = 2.0 * Math.random() - 1.0; - w = x1 * x1 + x2 * x2; - } while ( w >= 1.0 ); - - w = Math.sqrt( (-2.0 * Math.log( w ) ) / w ); - y1 = x1 * w; - y2 = x2 * w; - use_last = true; - } - - return( m + y1 * s ); - } - - public static function SanitizeNumber(n) - { - if (n is Number) - { - if (n == Number.NEGATIVE_INFINITY || n == Number.POSITIVE_INFINITY || n == Number.NaN) return 0; - } - return n; - } - - public static function IsNumberInvalid(n) - { - if (n is Number) - { - if (n == Number.NEGATIVE_INFINITY || n == Number.POSITIVE_INFINITY || n == Number.NaN) return true; - } - return false; - } - - public static function LimitNumberToMax(n) - { - if (n == Number.POSITIVE_INFINITY) return Number.MAX_VALUE; - return n; - } - - /* - value= Math.round(20/7); - value= int((20/7)*10)/10; - value= int((20/7)*100)/100; - value= int((20/7)*1000)/1000; - value= int((20/7)*10000)/10000; - */ - public static function RoundToDecimalPlaces(number:Number, places:int) - { - return Math.round((number)*Math.pow(10,places))/Math.pow(10,places); - } - - public static function GetShuffledArray(a:Array) : Array - { - var r:Array = a.concat(); - r.sort(randomSort); - return r; - } - - ///Convenience function since I keep forgetting the name of randomSort (hint: it's randomSort) - public static function ShuffleArray(a:Array) - { - a.sort(randomSort); - } - - public static function PickRandom(a:Array) - { - return a[Math.floor(Math.random() * a.length)]; - } - - /** - * Returns n elements of array a, up to a maximum of a's length. - * If forceCopy is set, the returned array will always be a new instance. - */ - public static function PickRandomSet(a:Array, n:int, forceCopy:Boolean=false):Array - { - if (a.length <= n || a.length == 0) - { - if (forceCopy) return a.concat(); - else return a; - } - if (n == 1) return [PickRandom(a)]; - - var shuffled:Array = GetShuffledArray(a); - return shuffled.slice(0, n); - } - - /** - * Does not randomly sort an array! To do that, Use the default array.sort with this as its argument. - * If you want a new, shuffled array, use GetShuffledArray - */ - public static function randomSort(a:*, b:*) : Number - { - if (Math.random() < 0.5) return -1; - else return 1; - } - - /** - * Returns the union of arr1 and arr2. If the elements are not primitive types, you'll need to provide a sorting function. - * If inPlace, a1 and a2 will be sorted. - * If they already contain duplicates, then all bets are off. - */ - public static function MergeArrays(arr1:Array, arr2:Array, sortFunc:Function = null, inPlace:Boolean = false) : Array - { - var ret:Array = []; - var a1:Array = (inPlace) ? arr1 : arr1.slice(); - var a2:Array = (inPlace) ? arr2 : arr2.slice(); - - var len1:uint = a1.length; - var len2:uint = a2.length; - var i1:uint = 0; - var i2:uint = 0; - - //Boring cases - if (len1 == 0 && len2 == 0) return ret; - if (len1 == 0) return (inPlace) ? a2.slice() : a2; - if (len2 == 0) return (inPlace) ? a1.slice() : a1; - - if (sortFunc) - { - a1.sort(sortFunc); - a2.sort(sortFunc); - } - else - { - a1.sort(); - a2.sort(); - } - - while (i1 < len1) - { - //add all from a2 up to a1[i1] - while (i2 < len2 && a2[i2] <= a1[i1]) - { - ret.push(a2[i2]); - i2 += 1; - } - if (ret.length == 0 || a1[i1] != ret[ret.length-1]) ret.push(a1[i1]); - i1 += 1; - } - - while (i2 < len2) ret.push(a2[i2]); - - return ret; - } - - public static function ConvertToHHMMSS(seconds:Number):String - { - var s:Number = seconds % 60; - var m:Number = Math.floor((seconds % 3600 ) / 60); - var h:Number = Math.floor(seconds / (60 * 60)); - - var hourStr:String = (h == 0) ? "" : DoubleDigitFormat(h) + ":"; - var minuteStr:String = DoubleDigitFormat(m) + ":"; - var secondsStr:String = DoubleDigitFormat(s); - - return hourStr + minuteStr + secondsStr; - } - - public static function DoubleDigitFormat(num:uint):String - { - if (num < 10) - { - return ("0" + num); - } - return String(num); - } - - public static function CapitolizeString(str:String) : String - { - var firstChar:String = str.substr(0, 1); - var restOfString:String = str.substr(1, str.length); - - return firstChar.toUpperCase()+restOfString.toLowerCase(); - } - - // ^ Nice spelling, goof! - public static function CapitalizeString(str:String) : String - { - return CapitolizeString(str); - } - - public static function GetListString(listStrings:Array) : String - { - var andString:String = "&"; - var count:int = 0; - - var listString:String = ""; - for (var i = 0; i < listStrings.length; i++) - { - if (count > 0 && listStrings.length == 2) listString += " "+andString+" "; // For just 2 items - else if (count == listStrings.length-1 && listStrings.length > 2) - { - // For adding "and" at the end of 3+ items. It is: ", and $(item)" - var endingString:String = ""; - endingString = endingString.replace("$(item)", listStrings[i]); - listString += endingString; - count++; - continue; - } - else if (count > 0) listString += ", "; // Comma separated list - - listString += listStrings[i]; - count++; - } - - return listString; - } - - /* - * Flash doesn't like the way MySQL prints dates (2016-06-02 13:00:00) - * "The year month and day terms can be separated by a forward slash (/) or by spaces, but never by a dash (-)." - */ - public static function ParseDate (dateString:String) : Date - { - var pattern:RegExp = /-/g; - var date = new Date(); - dateString = dateString.replace(pattern, "/"); - date.setTime(Date.parse(dateString)); - return date; - } - - /* - * For display only, not intended to be read by ParseDate - * Tuesday, June 7th, 2016 at 10:32 AM - */ - public static function FormatDate (date:Date) : String - { - var f:DateTimeFormatter = new DateTimeFormatter("en-US"); - var dateStr:String; - var lastChar:String; - - //Flash can't do "1st", "2nd", etc - - f.setDateTimePattern("d"); - dateStr = f.format(date); - lastChar = dateStr.charAt(dateStr.length - 1); - - if (lastChar == "1" && dateStr != "11") dateStr += "st"; - else if (lastChar == "2" && dateStr != "12") dateStr += "nd"; - else if (lastChar == "3" && dateStr != "13") dateStr += "rd"; - else dateStr += "th"; - - f.setDateTimePattern("EEEE, MMMM '" + dateStr + "', yyyy 'at' h:mm a"); - return f.format(date); - } - - /* Simply counts the number of properties on the object - */ - public static function CountObjectParameters(obj:Object):int - { - var cnt:int=0; - - for (var s:String in obj) cnt++; - - return cnt; - } - - /** - * For when shit gets real - */ - public static function PrintStackTrace() - { - try { - throw new Error('StackTrace'); - } catch (e:Error) { - _strace(e.getStackTrace()); - } - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/flash/util/RectangleNode.as b/flash/util/RectangleNode.as new file mode 100644 index 0000000..6f31e44 --- /dev/null +++ b/flash/util/RectangleNode.as @@ -0,0 +1,178 @@ +package util { + import flash.geom.Rectangle; + + public class RectangleNode + { + public var Left:RectangleNode = null; + public var Right:RectangleNode = null; + public var Rect:Rectangle = null; + public var InUse:Boolean = false; + public var Removed:Boolean = false; + public var Parent:RectangleNode = null; + public var AllocationID = 0; + public var Host:RectanglePacker= null; + public var MinAllocationID = 0; + public var NodeID; + public static var NextNodeID = 0; + + public var DontRemove = false; + + public var LastAccessTime = 0; + + public var Flags = []; + + public var UpdateTo:RectangleNode = null; + + /* + public function get Removed() + { + return _Removed; + } + + public function set Removed(r) + { + this._Removed = r; + } + + public function get Host():RectanglePacker + { + return _Host; + } + public function set Host(p:RectanglePacker) + { + this._Host = p; + + if (_Left && _Left.Host != p) + { + throw new Error("bad left host"); + } + if (_Right && _Right.Host != p) + { + throw new Error("bad right host"); + } + if (_Parent && _Parent.Host != p) + { + throw new Error("bad parent host"); + } + + } + + public function get Left():RectangleNode + { + return _Left; + } + public function set Left(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad left host"); + } + _Left = n; + } + public function get Right():RectangleNode + { + return _Right; + } + public function set Right(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad right host"); + } + _Right = n; + } + + public function get Parent():RectangleNode + { + return _Parent; + } + public function set Parent(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad parent host"); + } + _Parent = n; + } + */ + public function get IsFreeSpace() + { + return Left == null && Right == null && !InUse; + } + public function UpdateLinksFromNode(node:RectangleNode) + { + if (node.Parent) + { + if (node.Parent.Left == node) + { + node.Parent.Left = this; + } + if (node.Parent.Right == node) + { + node.Parent.Right = this; + } + } + if (node.Left) + { + node.Left.Parent = this; + } + if (node.Right) + { + node.Right.Parent = this; + } + } + public function MakeFromNode(node:RectangleNode) + { + //_Host = node.Host; + Host = node.Host; + Left = node.Left; + Right = node.Right; + Parent = node.Parent; + AllocationID = node.AllocationID; + InUse = node.InUse; + MinAllocationID = node.MinAllocationID; + NodeID = node.NodeID; + Rect = node.Rect.clone(); + Removed = node.Removed; + DontRemove = node.DontRemove; + } + public function RectangleNode(x, y, w, h, host:RectanglePacker) + { + this.NodeID = NextNodeID++; + this.Host = host; + this.Rect = new Rectangle(x, y, w, h); + } + public function OutputJSON() + { + var node = {}; + node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; + node.in_use = InUse; + node.id = NodeID; + if (this.Left) node.left = this.Left.OutputJSON(); + if (this.Right) node.right = this.Right.OutputJSON(); + return node; + } + + public function ReadJSON(details) + { + details.new_node = this; + this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); + this.Removed = false; + + this.InUse = details.in_use; + + if (details.hasOwnProperty("right")) + { + this.Right = new RectangleNode(0, 0, 0, 0, this.Host); + Right.ReadJSON(details.right); + Right.Parent = this; + } + if (details.hasOwnProperty("left")) + { + this.Left = new RectangleNode(0, 0, 0, 0, this.Host); + Left.ReadJSON(details.left); + Left.Parent = this; + } + } + } +} diff --git a/flash/util/RectanglePacker.as b/flash/util/RectanglePacker.as new file mode 100644 index 0000000..597d7fd --- /dev/null +++ b/flash/util/RectanglePacker.as @@ -0,0 +1,562 @@ +package util { + import flash.geom.*; + import flash.display.BitmapData; + import flash.display.MovieClip; + import flash.text.TextField; + import flash.events.*; + import flash.sampler.StackFrame; + + public class RectanglePacker + { + protected var w:int; + protected var h:int; + protected var root:RectangleNode; + public var NextAllocationID = 0; + + public function get width():int { return w; } + public function get height():int { return h; } + + public function RectanglePacker(w, h) + { + this.w = w; + this.h = h; + root = new RectangleNode(0, 0, w, h, this); + root.AllocationID = -1; + } + protected var area = 0; + + protected var testRender:MovieClip = new MovieClip(); + + public function GetRoot():RectangleNode + { + return root; + } + + public function GetLeafNodes():Array + { + return GetLeafNodesInternal(root); + } + + protected function GetLeafNodesInternal(n:RectangleNode):Array + { + if (n.InUse) return [n]; + var ret:Array = new Array(); + if (n.Left) ret = GetLeafNodesInternal(n.Left); + if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); + return ret; + } + + public function GetUsedArea() + { + return area; + } + + public function get efficiency() + { + return area / (w * h); + } + + protected function RectCost(w, h) + { + if (w == 0 || h == 0) return 99999999; + return (Math.max(w, h) / Math.min(w, h)) * w * h; + } + + protected function EnumerateTree(r:RectangleNode = null, indent = "") + { + if (r == null) r = this.root; + var str = ""; + str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; + if (r.Left) str += EnumerateTree(r.Left, indent + " "); + if (r.Right) str += EnumerateTree(r.Left, indent + " "); + return str; + } + + /* + * Remove a list of nodes from the tree. + * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree + * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, + leaving the original objects intact (in case something still references them) + */ + public function RemoveNodes(nodes:Array, fullyDestroy = true) + { + + /* DEBUG CHECKS */ + /* + this.PerformDebugCheck(); + + var str = ""; + for (var i = 0; i < nodes.length; i++) + { + str += nodes[i].NodeID + "\n"; + } + + var orig = nodes.concat(); + + var strs = [str, EnumerateTree()]; + + RenderDetailsBox.StartTrack("PackRemoveTime"); + + for (var i = 0; i < nodes.length; i++) + { + var n:RectangleNode = nodes[i]; + if (n.Host != this) + { + throw new Error("bad host!"); + } + } + */ + /* END DEBUG CHECKS */ + + var i, n:RectangleNode, p:RectangleNode; + + // setup the Removed flag on every node that should be removed + // we also check at this time to see if any more nodes need to be removed, such as a parent of + // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + if (n.Host == this) + { + n.Removed = true; + + if (n.InUse) + { + // sum up the total removed area + area -= n.Rect.width * n.Rect.height; + } + + if (n.Parent != null) + { + p = n.Parent; + // check and see if the current node's parent still has any valid children + if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) + { + // all of the current nodes siblings are either being removed or are blank, so + // we can remove the parent too + if (p.Left.IsFreeSpace) + { + // the left child was empty space before, so we can remove it (if it wasn't + // empty space it is already being removed so it doesn't need to be added + // to the list) + if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); + } + if (p.Right.IsFreeSpace) + { + // the right child was empty space before, so we can remove it + if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); + } + if (p != root && nodes.indexOf(p) == -1) + { + // remove the parent node too (provided it isn't the root!) + nodes.push(p); + } + } + } + } + } + + // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, + // so go ahead and remove them + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + + if (n.Parent != null) + { + // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not + // also getting removed!) + p = n.Parent; + + if (!p.Removed) + { + if (p.Left && p.Right) + { + var newNode:RectangleNode; + if (p.Left.Removed && p.Right.Removed) + { + // both children were removed, but the parent wasn't, so the parent must be root + // (since we never remove the root) + if (p != root) + { + throw new Error("should be root"); + } + p.Left.Parent = null; + p.Right.Parent = null; + p.Left = null; + p.Right = null; + p.InUse = false; + } else if (!p.Left.Removed) { + // Right node removed, Left node not removed + if (!p.Left.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Right); + newNode.UpdateLinksFromNode(p.Right); + } + // Left node is used + p.Right.InUse = false; + p.Right.Left = null; + p.Right.Right = null; + p.Right.Removed = false; + } else { + throw new Error("should have been caught above!"); + } + } else { + // Left node removed, Right node not removed + if (!p.Right.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Left); + newNode.UpdateLinksFromNode(p.Left); + } + // Left node is used + //p.Left.Removed = true; + p.Left.InUse = false; + p.Left.Left = null; + p.Left.Right = null; + p.Left.Removed = false; + //p.Left.Parent = null; + } else { + throw new Error("should have been caught above!"); + } + } + } else { + // huh? how does n.Parent == p but p has no children? something went wrong + throw new Error("shouldn't have gotten here"); + } + } + } + //strs.push(EnumerateTree()); + } + } + + public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode + { + + var node:RectangleNode = FindSizedNode(w, h, root); + + if (node == null) + { + //UHOH, texture full + return null; + } + area += w * h; + node.InUse = true; + + var splitVertFirstCost = 0; + if (w < node.Rect.width) + { + splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); + } + + var splitHorizFirstCost = 0; + if (h < node.Rect.height) + { + splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); + } + + + + if (splitVertFirstCost <= splitHorizFirstCost) + { + node.Flags.push("SplitVertFirst"); + if (w < node.Rect.width) + { + node.Flags.push("SplitVert"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + if (h < node.Rect.height) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + } else { + node.Flags.push("SplitHorzFirst"); + if (h < node.Rect.height) + { + node.Flags.push("SplitVert"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + if (w < node.Rect.width) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + } + NextAllocationID++; + if (useInstead) + { + useInstead.MakeFromNode(node); + useInstead.UpdateLinksFromNode(node); + useInstead.Flags = node.Flags; + node = useInstead; + node.Flags.push("UseInstead"); + } + + //if (!CheckOKNode(node)) node.Flags.push("BadNode"); + + return node; + } + public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) + { + if (r == null) r = this.root; + if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) + { + var ancestor:RectangleNode = FindCommonNode(n, r); + throw new Error("bad node allocated!"); + return false; + } + var ok = true; + if (r.Left) ok = ok && CheckOKNode(n, r.Left); + if (r.Right) ok = ok && CheckOKNode(n, r.Right); + return ok; + } + + public function PerformDebugCheck() + { + DebugInternal(this.root); + } + + protected function DebugInternal(n:RectangleNode) + { + if (n.Host != this) + { + throw new Error("problem with host!"); + } + if (n.IsFreeSpace) + { + if (n.Left || n.Right) + { + throw new Error("shouldn't have children"); + } + } + if ((n.Left && !n.Right) || (n.Right && !n.Left)) + { + throw new Error("mismatched children"); + } + if (n.Left && n.Left.Parent != n) + { + throw new Error("left child has bad parent"); + } + if (n.Right && n.Right.Parent != n) + { + throw new Error("right child has bad parent"); + } + if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) + { + throw new Error("problem with parent"); + } + if (n.Left) DebugInternal(n.Left); + if (n.Right) DebugInternal(n.Right); + } + + public function FindCommonNode(a:RectangleNode, b:RectangleNode) + { + var aHistory = []; + var bHistory = []; + while (a != null) + { + aHistory.push(a); + a = a.Parent; + } + while (b != null) + { + bHistory.push(b); + b = b.Parent; + } + var i = aHistory.length - 1; + var j = bHistory.length - 1; + var same = null; + while (i >= 0 && j >= 0) + { + if (aHistory[i] == bHistory[j]) + { + same = aHistory[i]; + } else { + break; + } + i--; + j--; + } + return same; + } + + public function TestRender() + { + while (testRender.numChildren > 0) + { + testRender.removeChildAt(0); + } + testRender.graphics.clear(); + TestRenderNode(root, testRender); + return testRender; + } + protected function TestRenderNode(n:RectangleNode, m:MovieClip) + { + var g:MovieClip = new MovieClip(); + m.addChild(g); + g.graphics.lineStyle(1, 0, 1); + if (n.Left != null) TestRenderNode(n.Left, m); + if (n.Left != null) TestRenderNode(n.Right, m); + if (n.InUse) + { + g.graphics.beginFill(0xFFFF00, 0.2); + } + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + if (n.InUse) + { + g.graphics.endFill(); + var t:TextField = new TextField(); + t.text = n.NodeID; + t.x = n.Rect.x + n.Rect.width / 2.0; + t.y = n.Rect.y + n.Rect.height / 2.0; + g.addChild(t); + g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); + g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); + } + + } + public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) + { + if (n.InUse) + { + //_trace(Math.round(n.LastAccessTime / 1000)); + } + var p:RectangleNode = n.Parent; + if (p) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); + g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); + g.graphics.endFill(); + t.text = p.NodeID; + if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); + g.oldListener = function(e){MouseOver(p, g, t);}; + g.addEventListener(MouseEvent.CLICK, g.oldListener); + } + } + public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(0xFFFF00, 0.2); + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + g.graphics.endFill(); + t.text = n.NodeID; + } + protected function SplitVert(node:RectangleNode, leftWidth) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function SplitHoriz(node:RectangleNode, topHeight) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode + { + if (node.InUse) return null; + if (node.Rect.width >= w && node.Rect.height >= h) + { + if (node.Left != null && node.Right != null) + { + var t:RectangleNode = FindSizedNode(w, h, node.Left); + if (t != null) return t; + t = FindSizedNode(w, h, node.Right); + return t; + } else { + return node; + } + } + return null; + } + + public function LoadTree(details) + { + this.root = new RectangleNode(0, 0, 0, 0, this); + root.ReadJSON(details); + + this.NextAllocationID = 0; + this.area = 0; + + var queue:Array = new Array(); + queue.push(root); + while (queue.length > 0) + { + var node:RectangleNode = queue.shift(); + node.AllocationID = NextAllocationID; + node.MinAllocationID = NextAllocationID; + if (node.Left) queue.push(node.Left); + if (node.Right) queue.push(node.Right); + if (node.InUse) this.area += node.Rect.width * node.Rect.height; + } + NextAllocationID++; + } + + public function GetNodePath(node:RectangleNode) + { + var output:String = ""; + while (node != this.root) + { + output = (node == node.Parent.Left ? "l" : "r") + output; + node = node.Parent; + } + return output; + } + + public function GetNodeFromPath(path:String):RectangleNode + { + var node:RectangleNode = this.root; + for (var i = 0; i < path.length; i++) + { + if (!node) return null; + if (path.charAt(i) == "r") + { + node = node.Right; + } else { + node = node.Left; + } + } + return node; + } + } +} diff --git a/flash/util/Utils.as b/flash/util/Utils.as new file mode 100644 index 0000000..f792003 --- /dev/null +++ b/flash/util/Utils.as @@ -0,0 +1,389 @@ +package util +{ + import flash.display.*; + import flash.geom.*; + public class Utils + { + public static function GetChildren(clip:MovieClip):Array + { + var ret:Array = []; + for (var i = 0; i < clip.numChildren; i++) + { + ret.push(clip.getChildAt(i)); + } + return ret; + } + + /* + * angle difference + * (range -Math.PI to Math.PI) + */ + public static function GetAngleDiff(a, b) + { + var angleDiff = b - a; + + while (angleDiff > Math.PI) + { + angleDiff -= Math.PI * 2; + } + while (angleDiff < -Math.PI) + { + angleDiff += Math.PI * 2; + } + return angleDiff; + } + + /* + * angle difference + * (range 0 to Math.PI) + */ + public static function GetAngleDiffAbs(a, b) + { + var angleDiff = GetAngleDiff(a, b); + while (angleDiff < 0) + { + angleDiff += Math.PI * 2; + } + + if (angleDiff > Math.PI) + { + angleDiff = Math.PI * 2 - angleDiff; + } + + return angleDiff; + } + + public static function GetTransform(from:Matrix, to:Matrix) + { + var i:Matrix = from.clone(); + i.invert(); + var m:Matrix = to.clone(); + m.concat(i); + return m; + } + + public static function Decompose(m:Matrix) + { + var s:Point = ScaleFromMat(m); + m = m.clone(); + + var sxUnit = s.x >= 0 ? 1 : -1; + var syUnit = s.y >= 0 ? 1 : -1; + + m.scale(sxUnit, syUnit); + + //m.a /= sxUnit; + //m.d /= syUnit; + var rot = RotFromMat(m); + return {sx:s.x, sy:s.y, rot:rot}; + } + + public static function RotFromMat(m:Matrix) + { + return Math.atan2(-m.c, m.a); + } + + public static function ScaleFromMat(m:Matrix):Point + { + var xAxisX = m.a; + var xAxisY = m.c; + + var yAxisX = m.b; + var yAxisY = m.d; + + var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); + if (m.a < 0) sx *= -1; + + var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); + if (m.d < 0) sy *= -1; + + return new Point(sx, sy); + } + + public static function TransformRect(r:Rectangle, m:Matrix) + { + var p1:Point = new Point(r.left, r.top); + var p2:Point = new Point(r.right, r.top); + var p3:Point = new Point(r.left, r.bottom); + var p4:Point = new Point(r.right, r.bottom); + + p1 = m.transformPoint(p1); + p2 = m.transformPoint(p2); + p3 = m.transformPoint(p3); + p4 = m.transformPoint(p4); + + r.left = Math.min(p1.x, p2.x, p3.x, p4.x); + r.top = Math.min(p1.y, p2.y, p3.y, p4.y); + r.right = Math.max(p1.x, p2.x, p3.x, p4.x); + r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); + } + + public static function RoundRect(r:Rectangle) + { + r.left = Math.floor(r.left); + r.top = Math.floor(r.top); + r.right = Math.ceil(r.right); + r.bottom = Math.ceil(r.bottom); + } + + public static function ScaleRect(r:Rectangle, s) + { + r.left *= s; + r.top *= s; + r.right *= s; + r.bottom *= s; + } + + public static function RecursivelyStop(clip) + { + if (clip is MovieClip) + { + clip.stop(); + } + if (clip is DisplayObjectContainer) + { + for (var i = 0; i < clip.numChildren; i++) + { + RecursivelyStop(clip.getChildAt(i)); + } + } + } + + public static function WeirdGotoFrame(clip:MovieClip, frame) + { + var dir = clip.currentFrame > frame ? -1 : 1; + while (clip.currentFrame != frame) + { + RecurseDir(clip, dir); + } + } + + protected static function RecurseDir(clip:MovieClip, dir) + { + for (var i = 0; i < clip.numChildren; i++) + { + var child = clip.getChildAt(i); + if (child is MovieClip) + { + RecurseDir(child, dir); + } + } + if (dir == 1) + { + clip.nextFrame(); + } else { + clip.prevFrame(); + } + } + + protected static var tempSpace:BitmapData = null; + protected static var tempSpaceRect:Rectangle = new Rectangle(); + protected static var tempSpaceMatrix:Matrix = new Matrix(); + protected static var tempSpaceZero:Point = new Point(); + protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); + protected static var lastDrawOffset:Point = new Point(); + public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle + { + if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); + + var oldPad = 0; + var padAmount = 5; + + var ret:Rectangle = new Rectangle(); + + var baseBounds:Rectangle = clip.getBounds(clip); + + var boundsClip:DisplayObject = null; + if (clip is DisplayObjectContainer) + { + boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); + } + + if (boundsClip != null) + { + baseBounds = boundsClip.getBounds(clip); + } + + if (useMatrix) + { + TransformAABBRect(baseBounds, useMatrix); + } + + if (boundsClip != null) + { + return baseBounds; + } + + var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); + var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); + if (tempSpace == null) + { + tempSpace = new BitmapData(minW, minH, true, 0x0); + } + if (tempSpace.width < minW || tempSpace.height < minH) + { + tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); + } + + var r:Rectangle = new Rectangle(); + + baseBounds.left = Math.floor(baseBounds.left); + baseBounds.right = Math.ceil(baseBounds.right); + + baseBounds.top = Math.floor(baseBounds.top); + baseBounds.bottom = Math.ceil(baseBounds.bottom); + + var i; + + var needsChecking = true; + while (needsChecking) + { + needsChecking = false; + r.left = baseBounds.left - padAmount; + r.right = baseBounds.right + padAmount; + + r.top = baseBounds.top - padAmount; + r.bottom = baseBounds.bottom + padAmount; + + ret = r.clone(); + + tempSpaceRect.x = tempSpaceRect.y = 0; + tempSpaceRect.width = tempSpace.width; + tempSpaceRect.height = tempSpace.height; + tempSpace.fillRect(tempSpaceRect, 0x0); + + tempSpaceMatrix.identity(); + if (useMatrix) + { + tempSpaceMatrix.a = useMatrix.a; + tempSpaceMatrix.b = useMatrix.b; + tempSpaceMatrix.c = useMatrix.c; + tempSpaceMatrix.d = useMatrix.d; + tempSpaceMatrix.tx = useMatrix.tx; + tempSpaceMatrix.ty = useMatrix.ty; + } + tempSpaceMatrix.translate(-r.left, -r.top); + + lastDrawOffset.x = -r.left; + lastDrawOffset.y = -r.top; + tempSpace.draw(clip, tempSpaceMatrix); + + tempSpaceRect.width = 1; + tempSpaceRect.height = r.height; + + var sideMovedIn = 0; + for (i = 0; i < r.width; i++) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.left++; + sideMovedIn++; + } + } + if (ret.left < baseBounds.left - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.width - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.right--; + } + } + if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + sideMovedIn = 0; + tempSpaceRect.width = r.width; + tempSpaceRect.height = 1; + tempSpaceRect.x = 0; + for (i = 0; i < r.height; i++) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.top++; + sideMovedIn++; + } + } + if (ret.top < baseBounds.top - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.height - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.bottom--; + } + } + if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + } + return ret; + } + + public static function TransformAABBRect(r:Rectangle, m:Matrix) + { + var o1X = r.left; + var o1Y = r.top; + + var o2X = r.right; + var o2Y = r.top; + + var o3X = r.left; + var o3Y = r.bottom; + + var o4X = r.right; + var o4Y = r.bottom; + + var n1X = o1X * m.a + o1Y * m.c + m.tx; + var n1Y = o1X * m.b + o1Y * m.d + m.ty; + + var n2X = o2X * m.a + o2Y * m.c + m.tx; + var n2Y = o2X * m.b + o2Y * m.d + m.ty; + + var n3X = o3X * m.a + o3Y * m.c + m.tx; + var n3Y = o3X * m.b + o3Y * m.d + m.ty; + + var n4X = o4X * m.a + o4Y * m.c + m.tx; + var n4Y = o4X * m.b + o4Y * m.d + m.ty; + + r.left = Math.min(n1X, n2X, n3X, n4X); + r.right = Math.max(n1X, n2X, n3X, n4X); + + r.top = Math.min(n1Y, n2Y, n3Y, n4Y); + r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); + } + } +} diff --git a/job.py b/job.py index 989c991..77c09e8 100644 --- a/job.py +++ b/job.py @@ -3,6 +3,7 @@ import json from validate import * from args import * +import copy asset_src_schema = { "type":"object", @@ -69,19 +70,24 @@ base_path = os.path.join(self.out_dir, self.rel_path) if not os.path.exists(base_path): os.makedirs(base_path) + resource_names = [] for i,r in enumerate(resources): - path = os.path.join(base_path, "%s_%04d.png" % (self.name, i)) + resource_name = "%s_%04d.png" % (self.name, i) if len(resources) > 1 else self.name + ".png" + resource_names.append(resource_name) + path = os.path.join(base_path, resource_name) with open(path, "wb") as f: f.write(base64.b64decode(r)) if len(data) == 1: graphic_and_asset = {} (name, graphic_data) = data.items()[0] - graphic_and_asset = {"data":graphic_data} + graphic_and_asset = {"data":graphic_data, "resources":resource_names} with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps(graphic_and_asset)) else: + write_data = copy.deepcopy(data) + write_data["resources"] = resource_names with open(os.path.join(base_path, self.name + ".asset"), "w") as f: - f.write(pretty_dumps(data)) + f.write(pretty_dumps(write_data)) for name,details in data.iteritems(): with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps({"data":self.name + ".asset"})) diff --git a/old/Checkbox.as b/old/Checkbox.as deleted file mode 100644 index c5aaba2..0000000 --- a/old/Checkbox.as +++ /dev/null @@ -1,42 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - - public class Checkbox extends MovieClip - { - public var Enabled:Boolean = true; - public function Checkbox() - { - checkbox.gotoAndStop(1); - checkbox.addEventListener(MouseEvent.CLICK, Clicked); - } - - protected function Clicked(event) - { - if (!Enabled) return; - Toggle(); - if (OnClick != null) OnClick(OnClickParam); - } - - protected var checked = false; - public function set Checked(value) { checked = value; checkbox.gotoAndStop(checked ? 2 : 1); } - public function get Checked() { return checked; } - - public function set Text(value) { text.text = value; } - - public var OnClickParam; - public var OnClick; - - - public function Toggle() - { - checked = !checked; - checkbox.gotoAndStop(checked ? 2 : 1); - - - } - - } - -} diff --git a/old/GraphicExport-app.xml b/old/GraphicExport-app.xml deleted file mode 100644 index 5144634..0000000 --- a/old/GraphicExport-app.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - GraphicExport - 1.0 - GraphicExport - - GraphicExport - - - GraphicExport.swf - standard - false - true - false - portrait - auto - true - true - true - - - false - false - desktop extendedDesktop diff --git a/old/GraphicExport.exe b/old/GraphicExport.exe deleted file mode 100644 index 56315aa..0000000 --- a/old/GraphicExport.exe +++ /dev/null Binary files differ diff --git a/old/GraphicExport.fla b/old/GraphicExport.fla deleted file mode 100644 index 0b78ed7..0000000 --- a/old/GraphicExport.fla +++ /dev/null Binary files differ diff --git a/old/GraphicExport.swf b/old/GraphicExport.swf deleted file mode 100644 index 542db97..0000000 --- a/old/GraphicExport.swf +++ /dev/null Binary files differ diff --git a/old/NewGraphicDialog.as b/old/NewGraphicDialog.as deleted file mode 100644 index 152011c..0000000 --- a/old/NewGraphicDialog.as +++ /dev/null @@ -1,224 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - import flash.events.*; - import flash.filesystem.File; - import flash.net.FileFilter; - import Defs.GraphicDef; - import flash.text.engine.GraphicElement; - - public class NewGraphicDialog extends MovieClip - { - - public function NewGraphicDialog() - { - // constructor code - Init(); - } - - var typeButtons:Array = new Array(); - - public function Init() - { - graphicPath.text = "Path to Graphic Here"; - - this.removeChild(browseButton); - - var newBrowseButton = new UI_GenericBlueButton(); - newBrowseButton.Text = "Browse"; - newBrowseButton.OnClick = BrowseForFile; - newBrowseButton.x = browseButton.x + (newBrowseButton.width / 2); - newBrowseButton.y = browseButton.y + (newBrowseButton.height / 2); - addChild(newBrowseButton); - - var newTestButton = new UI_GenericBlueButton(); - newTestButton.Text = "Export"; - newTestButton.OnClick = TestFile; - newTestButton.x = testButton.x + (newTestButton.width / 2); - newTestButton.y = testButton.y + (newTestButton.height / 2); - addChild(newTestButton); - - this.removeChild(typePlaceholderButton); - - var typeX = typePlaceholderButton.x; - var typeY = typePlaceholderButton.y + (typePlaceholderButton.height / 2); - - - var typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Graphic (1)"; - typeButton.OnClick = function(){ SetType(1); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Skeletal (3)"; - typeButton.OnClick = function(){ SetType(3); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Scene (6)"; - typeButton.OnClick = function(){ SetType(6); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - animationCheckbox.Checked = true; - //browseButton - //typePlaceholderButton - //usesInput - //usesText.text = "" - } - - var usesInputDefaultText = "Comma Seperated List of Uses Here"; - - public static var fakeID = 9999999; - public function TestFile() - { - fakeID++; - var graphicName = graphicPath.text; - var graphicData = {id:fakeID,graphic:graphicPath.text,v:1,fs:0,p:0,type:selectedType}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new GraphicDef(graphicData); - - this.Hide(); - graphicExport.ExportItem(graphicDef); - } - - var selectedType = 1; - public function SetType(type:Number) - { - selectedType = type; - - for(var i = 0; i < typeButtons.length; i++) - { - typeButtons[i].Enabled = true; - } - - animationCheckbox.visible = false; - - switch(type) - { - case 1: { - typeButtons[0].Enabled = false; - animationCheckbox.visible = true; - break; - } - case 3: typeButtons[1].Enabled = false; break; - case 6: typeButtons[2].Enabled = false; break; - } - } - - var graphicExport:GraphicExport; - public function Show(parentClip) - { - this.graphicExport = parentClip; - - parentClip.addChild(this); - - SetType(selectedType); - - var graphicList = GameData.Instance().GraphicDefines; - - var usesString:String = ""; - var uniqueUseTypes:Array = new Array(); - for (var i = 0; i < graphicList.length; i++) - { - var graphicDef:GraphicDef = graphicList[i]; - var uses = graphicDef.ExportParams['uses']; - for (var usage in uses) - { - if (uniqueUseTypes[uses[usage]] == null) - { - uniqueUseTypes[uses[usage]] = uses[usage]; - usesString += uses[usage] + ", "; - } - } - } - - graphicPath.text = ""; - - } - - public function CloseClicked(event) - { - Hide(); - } - - public function Hide() - { - if (this.parent != null) this.parent.removeChild(this); - } - - public function BrowseForFile() - { - var file:File = new File(); - var swfTypeFilter:FileFilter = new FileFilter("SWF Files","*.swf"); - file.addEventListener(Event.SELECT, openFile); - file.browse([swfTypeFilter]); - } - - private function openFile(event:Event):void - { - _strace(event.target.nativePath); - var path:String = event.target.nativePath; - var pathParts:Array = path.split("Graphics\\"); - if (pathParts.length == 2) - { - var fileRemainder:String = pathParts[1]; - var withoutExtension:String = fileRemainder.split(".")[0]; - var pattern:RegExp = /\\/g; - withoutExtension = withoutExtension.replace(pattern, "/"); - _strace(withoutExtension); - graphicPath.text = withoutExtension; - - if (withoutExtension.indexOf("Backgrounds") > -1) - { - SetType(6); - } - - if (withoutExtension.indexOf("Monsters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Characters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Portraits") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Quest") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Equipment") > -1) - { - SetType(1); - } - - - } - } - - - } - -} diff --git a/old/PNGExportHelper.as b/old/PNGExportHelper.as deleted file mode 100644 index f8c4c9d..0000000 --- a/old/PNGExportHelper.as +++ /dev/null @@ -1,253 +0,0 @@ -package -{ - import flash.display.*; - import com.adobe.images.*; - import flash.utils.*; - import flash.net.*; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import flash.geom.Point; - - public class PNGExportHelper - { - public static var UseExpandedBitmaps = false; - public static var AlphaThreshold = 5; - - private static function ExpandBitmapBorders(bd:BitmapData, bgColor = 0x0, passes = 1):BitmapData - { - /* - var thresh:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - thresh.threshold(bd, bd.rect, new Point(), "<", (20 << 24), bgColor, 0xFF000000, true); - */ - var sampled:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - bd.lock(); - sampled.lock(); - - for (var y = 0; y < bd.height; y++) - { - for (var x = 0; x < bd.width; x++) - { - var oldVal:uint = bd.getPixel32(x, y); - var a:uint = (oldVal & 0xFF000000) >>> 24; - var rgb:uint = (oldVal & 0xFFFFFF); - if (a > AlphaThreshold) - { - sampled.setPixel32(x, y, (0xFF << 24) | rgb); - } - else - { - sampled.setPixel32(x, y, bgColor); - } - } - } - sampled.unlock(); - bd.unlock(); - - return ExpandBitmapBordersInternal(sampled, bgColor, passes); - } - - private static function ExpandBitmapBordersInternal(bd:BitmapData, bgColor, passes):BitmapData - { - var output:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - - var scale = 16; - var scaled:BitmapData = new BitmapData(bd.width/scale, bd.height/scale, true, bgColor); - var mat:Matrix = new Matrix(); - mat.scale(1/scale, 1/scale); - scaled.draw(bd, mat, null, null, null, true); - - output.lock(); - - var colors:Array = new Array(); - var weights:Array = new Array(); - - for (var oy = 0; oy < scaled.height; oy++) - { - - for (var ox = 0; ox < scaled.width; ox++) - { - - var scaledVal:uint = scaled.getPixel32(ox, oy); - var scaleda:uint = (scaledVal & 0xFF000000) >>> 24; - if (scaleda == 0 || scaleda == 255) - { - output.copyPixels(bd, new Rectangle(ox * scale, oy * scale, scale, scale), new Point(ox * scale, oy * scale)); - continue; - } else { - //_strace(scaleda+""); - } - - - for (var y = oy * scale; y < oy * scale + scale; y++) - { - for (var x = ox * scale; x < ox * scale + scale; x++) - { - var oldVal:uint = bd.getPixel32(x, y); - var a:uint = (oldVal & 0xFF000000) >>> 24; - var rgb:uint = (oldVal & 0xFFFFFF); - - if (a == 0 && rgb == bgColor) - { - colors.length = 0; - weights.length = 0; - - for (var y1 = y - 2; y1 <= y + 2; y1++) - { - for (var x1 = x - 2; x1 <= x + 2; x1++) - { - var dist = Math.abs(x1 - x) + Math.abs(y1 - y); - if (dist >= 3) continue; - - if (x1 >= 0 && x1 < bd.width && y1 >= 0 && y1 < bd.height) - { - colors.push(bd.getPixel(x1, y1)); - weights.push(1 - dist * 0.2); - } - } - } - - var newVal = AveragePixels(colors, weights, bgColor); - if (newVal == null) - { - newVal = oldVal; - } - else - { - var newR:uint = (newVal & 0xFF0000) >> 16; - var newG:uint = (newVal & 0xFF00) >> 8; - var newB:uint = (newVal & 0xFF); - - if (newVal != 0 && colors.length >= 4) - { - var bp = true; - } - - var sorted = colors.sort(function(a, b) - { - var aR:uint = (a & 0xFF0000) >> 16; - var aG:uint = (a & 0xFF00) >> 8; - var aB:uint = (a & 0xFF); - - var bR:uint = (b & 0xFF0000) >> 16; - var bG:uint = (b & 0xFF00) >> 8; - var bB:uint = (b & 0xFF); - - var diffA = Math.abs(aR - newR) + Math.abs(aG - newG) + Math.abs(aB - newB); - var diffB = Math.abs(bR - newR) + Math.abs(bG - newG) + Math.abs(bB - newB); - - return diffA - diffB; - - }, Array.RETURNINDEXEDARRAY | Array.DESCENDING); - - var toRemove = Math.min(2, colors.length - 4); - var removed = 0; - for (var i = 0; i < colors.length; i++) - { - var index = sorted.indexOf(i + removed); - if (index < toRemove) - { - colors.splice(i, 1); - weights.splice(i, 1); - removed++; - i--; - if (removed == toRemove) break; - } - } - - var fixOutliersVal = AveragePixels(colors, weights, bgColor); - if (fixOutliersVal == null) newVal = (0xFF << 24) | newVal; - - newVal = (0xFF << 24) | fixOutliersVal; - } - - output.setPixel32(x, y, newVal); - } - else - { - output.setPixel32(x, y, oldVal); - } - } - } - }//end outer scaled x - }//End outer scaled y - - bd.unlock(); - output.unlock(); - - passes--; - if (passes > 0) - { - return ExpandBitmapBordersInternal(output, bgColor, passes); - } - else - { - return output; - } - } - - private static function AveragePixels(colors:Array, weights:Array, bgColor:uint):uint - { - var rTotal = 0; - var gTotal = 0; - var bTotal = 0; - - var wTotal = 0; - - for (var i = 0; i < colors.length; i++) - { - var color:uint = colors[i]; - var a:uint = (color & 0xFF000000) >>> 24; - var rgb:uint = (color & 0xFFFFFF); - - if (a == 0 && rgb == bgColor) - { - colors.splice(i, 1); - weights.splice(i, 1); - i--; - continue; - } - - var r:uint = (rgb & 0xFF0000) >>> 16; - var g:uint = (rgb & 0xFF00) >>> 8; - var b:uint = (rgb & 0xFF); - var w = weights[i]; - - rTotal += w * r; - gTotal += w * g; - bTotal += w * b; - - wTotal += w; - } - - if (wTotal == 0) - { - return null; - } - - rTotal /= wTotal; - gTotal /= wTotal; - bTotal /= wTotal; - - var rFinal = Math.max(0, Math.min(255, Math.round(rTotal))); - var gFinal = Math.max(0, Math.min(255, Math.round(gTotal))); - var bFinal = Math.max(0, Math.min(255, Math.round(bTotal))); - - return (uint(rFinal) << 16) | (uint(gFinal) << 8) | (uint(bFinal)); - } - - - - public static function GetExportPNG(bd:BitmapData):ByteArray - { - if (!UseExpandedBitmaps) return PNGEncoder.encode(bd); - - var expanded:BitmapData = ExpandBitmapBorders(bd, 0x0, 2); - - //var fr:FileReference = new FileReference(); - //fr.save(PNGEncoder.encode(expanded), "output.png"); - - return PNGEncoderWithAlpha.encode(expanded, bd); - } - - } -} \ No newline at end of file diff --git a/old/PreviewHolder.as b/old/PreviewHolder.as deleted file mode 100644 index 587bf68..0000000 --- a/old/PreviewHolder.as +++ /dev/null @@ -1,57 +0,0 @@ -package { - import flash.display.MovieClip; - - public class PreviewHolder extends MovieClip - { - - var startingWidth = 1024; - var startingHeight = 1024; - - public function PreviewHolder() - { - startingWidth = this.width; - startingHeight = this.height; - } - - var clips:Array = new Array(); - public function AddClip(clip) - { - clips.push(clip); - this.addChild(clip); - ArrangeClips(); - } - - public function ArrangeClips() - { - var numCols = Math.ceil(Math.sqrt(clips.length)); - var maxY = 0; - var maxX = 0; - var clipIndex = 0; - for (var row = 0; row < numCols; row++) - { - var clipX = 0; - var clipY = maxY; - for (var col = 0; col < numCols; col++) - { - if (clipIndex == clips.length) break; - clips[clipIndex].x = clipX; - clips[clipIndex].y = clipY; - clipX += clips[clipIndex].width; - var clipBottom = clips[clipIndex].y + clips[clipIndex].height; - if (clipBottom > maxY) maxY = clipBottom; - - var clipRight = clips[clipIndex].x + clips[clipIndex].width; - if (clipRight > maxX) maxX = clipRight; - clipIndex++; - } - } - - var scale = Math.min(startingWidth / maxX, startingHeight / maxY); - if (scale > 1) scale = 1; - - this.scaleX = this.scaleY = scale; - } - - } - -} diff --git a/old/Utils.as b/old/Utils.as deleted file mode 100755 index 02b4f12..0000000 --- a/old/Utils.as +++ /dev/null @@ -1,1202 +0,0 @@ -package old -{ - /* This class has functions similar to the Utils.as in the /flash/Dialogs folder. However, some of - * those functions are different here than in /flash/Dialogs/Utils.as for... reasons? flash folder reasons! - */ - import flash.utils.*; - import flash.net.*; - import flash.display.*; - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.geom.Point; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import flash.geom.ColorTransform; - import fl.motion.Color; - import fl.transitions.Tween; - import fl.transitions.easing.*; - import fl.transitions.TweenEvent; - import flash.net.navigateToURL; - import flash.external.ExternalInterface; - import flash.system.Capabilities; - import flash.filters.*; - import flash.filters.ColorMatrixFilter; - import com.adobe.images.JPGEncoder; - import flash.globalization.DateTimeFormatter; - - import djarts.utils.Base64; - import djarts.utils.PNGEnc; - import User.UserOptions; - - public class Utils - { - //["K","M","B","T","q", "Q", "s", "S","O","N","d","U","D","!","@","#","$","%","^","&","*"] - static var symbols = ["K","M","B","t","q", "Q", "s", "S","o","n","d","U","D","T","Qt","Qd","Sd","St","O","N","v","c"]; - static var divisors = []; - - public static function FormatBigNumber(number:*, round:Boolean=false):String - { - if (number < 0) return '-' + FormatBigNumber(Math.abs(number), round); - - var isWholeNumber = (Math.floor(number) == number); - round = round || isWholeNumber; - - if (number < 1000) - { - if (round) - { - return Math.round(number).toString(); - } - else - { - var decimalPlaces = (number >= 100) ? 1 : 2; // Below 100, show two decimal places. Above, only one. - var roundMult = Math.pow(10, decimalPlaces); - var rounded = Math.round(number); - var bigRounded = Math.round(number * roundMult); - var roundedDifferenceProportion = Math.abs(bigRounded / roundMult - rounded) / rounded; - - if (roundedDifferenceProportion < 0.001) - { - // Not a whole number, but the decimal places aren't worth showing - // Below also handles this, but is slower - return rounded.toString(); - } - else - { - var str:String = bigRounded.toString(); - str = str.substr(0, str.length - decimalPlaces) + "." + str.substr(str.length - decimalPlaces); - - while (str.charAt(str.length - 1) == "0") str = str.substr(0, str.length - 1); //should only ever happen once - if (str.charAt(str.length - 1) == ".") str = str.substr(0, str.length - 1); //probably won't happen at all - - return str; - } - } - } - - // Determine which symbol to use - var power = Math.floor(Math.log(number) / Math.log(1000)); - var index = Math.min(power-1, symbols.length-1); - var amount = number / Math.pow(1000, index+1); - var symbol = (index >= 0 && index < symbols.length) ? symbols[index] : ""; - - // If it's too big for a symbol (or if we just WANT to) - if (amount >= 1000 || UserOptions.ForceScientific) - { - // scientific notation - var power = Math.floor(Math.log(number) / Math.log(10)); - var num = number / Math.pow(10, power); - if (num == 10) { - num = 1; - power += 1; - } - var numString = "" + num; - numString = numString.substr(0, Math.min(4, numString.length)); - return numString + "e" + power; - - } - else - { - // Format with the symbol - // determine number of whole digits (will dictate how many decimals we show) - var whole = Math.floor(amount); - var amount_str:String = String(whole); - - var decimalDivider = 100/Math.pow(10,amount_str.length-1); - - //round to nearest decimal place - amount = int(amount*decimalDivider)/decimalDivider; - - var amountString:String = amount.toString(); - - var noDecimal:String = amountString.replace(".",""); - if (noDecimal.length == 2) - { - if (amountString.indexOf(".") != -1) amountString += "0"; - else amountString += ".0"; - } - else if (noDecimal.length == 1) amountString += ".00"; - - return amountString+symbol; // concat symbol - } - } - - private static var BigNumberRegex = new RegExp(/(\d*),?(\d*)(.*)/); - // Note-DG: This is mostly just used for definitions in the database, that don't require precision. - // This way we can define values in the database as 100B instead of 100000000000. - public static function ParseBigNumberString(number:String):Number - { - var regexArray:Array = BigNumberRegex.exec(number); - var magnitude = symbols.indexOf(regexArray[3]); - var thousands:Number; - if (regexArray[1]) { - thousands = regexArray[1]; - if (regexArray[2]) { // if numbers are split by comma, multiply by 1000 - thousands *= 1000; - } - } else { - thousands = 0; - } - var hundreds:Number = regexArray[2] ? regexArray[2] : 0; - - return (thousands + hundreds) * Math.pow(1000, magnitude + 1); - } - - public static function ParseNumberRange(range:String):Array - { - var split:Array = range.split(','); - return [Number(split[0]), Number(split[1])]; - } - - public static function DesaturateFilter() - { - var desatMatrix:Array = []; - var cmFilter; - - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // red - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // green - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // blue - desatMatrix = desatMatrix.concat([0, 0, 0, 1, 0]); // alpha - cmFilter = new ColorMatrixFilter(desatMatrix); - - return cmFilter; - } - - public static function GetUserAgent():String - { - try - { - var userAgent = ExternalInterface.call("window.navigator.userAgent.toString"); - var browser:String = "[Unknown Browser]"; - - if (userAgent.indexOf("Safari") != -1) - { - browser = "Safari"; - } - if (userAgent.indexOf("Firefox") != -1) - { - browser = "Firefox"; - } - if (userAgent.indexOf("Chrome") != -1) - { - browser = "Chrome"; - } - if (userAgent.indexOf("MSIE") != -1) - { - browser = "Internet Explorer"; - } - if (userAgent.indexOf("Opera") != -1) - { - browser = "Opera"; - } - } - catch (e:Error) - { - //could not access ExternalInterface in containing page - return "[No ExternalInterface]"; - } - - return browser; - } - - public static function GetScreenshot(stage:Stage):String { - var scale:Number = 0.25; - var result:String = null; - var blurFilter:BlurFilter = new BlurFilter(3, 3, BitmapFilterQuality.HIGH); - - var bData:BitmapData = new BitmapData(stage.stageWidth * scale, - stage.stageHeight * scale, false, 0x348400); - var matrix:Matrix = new Matrix(); - matrix.scale(scale, scale); - - bData.draw(stage, matrix); - bData.applyFilter(bData, bData.rect, new Point(0, 0), blurFilter); - - - var imgBytes:ByteArray = new JPGEncoder(80).encode(bData); - //var imgBytes:ByteArray = PNGEnc.encode(bData); - if (imgBytes) { - var screenshotBase64:String = Base64.encode(imgBytes); - if (screenshotBase64) { - result = screenshotBase64; - } - } - - return result; - } - - public static function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function PlayerVersion() - { - - // Get the player's version by using the getVersion() global function. - var versionNumber:String = Capabilities.version; - - // The version number is a list of items divided by "," - var versionArray:Array = versionNumber.split(","); - var length:Number = versionArray.length; - //for(var i:Number = 0; i < length; i++) _strace("versionArray["+i+"]: "+versionArray[i]); - - // The main version contains the OS type too so we split it in two - // and we'll have the OS type and the major version number separately. - var platformAndVersion:Array = versionArray[0].split(" "); - //for(var j:Number = 0; j < 2; j++) _strace("platformAndVersion["+j+"]: "+platformAndVersion[j]); - //_strace("-----"); - - var majorVersion:Number = parseInt(platformAndVersion[1]); - var minorVersion:Number = parseInt(versionArray[1]); - var buildNumber:Number = parseInt(versionArray[2]); - - return Number(majorVersion+"."+minorVersion); - } - - - public static function OpenLocalURLTop(url) - { - navigateToURL(new URLRequest(GameSettings.Approot+url), "_top" ); - } - - public static function OpenLocalURL(url) - { - navigateToURL(new URLRequest(GameSettings.Approot+url), "_blank" ); - } - - public static function OpenURL(url, window = "_blank") - { - navigateToURL(new URLRequest(url), window); - } - - public static var ExitFullScreenCallback; - - public static function WallPublish(title:String, desc1:String, desc2:String, image:String, url = null, action = null) - { - if (Utils.ExitFullScreenCallback) Utils.ExitFullScreenCallback(); - //_strace(title + "\n" + desc1 + "\n" + desc2 + "\n" + image + "\n"); - ExternalInterface.call("askToPublish", title, url, desc1, desc2, image, action); - - //if (Settings.Platform == Settings.HI5) { - //DialogManager.Instance().ShowMessageBox("The message was posted to your wall!", "", "OK", null); - //} - } - - public static function SendToRecipients(recipients:Array, description, data) - { - if (!GameSettings.IsFacebook) return; - - if (Utils.ExitFullScreenCallback) Utils.ExitFullScreenCallback(); - try { - ExternalInterface.call("sendToRecipients", recipients, description ,data); - } - catch (e) - { - _strace(e.message); - } - } - - - public static function GetFriendData() - { - try { - return ExternalInterface.call("pollInviteData"); - } - catch (e) - { - _strace(e.message); - } - } - - - public static function singleBounceEase(t:Number, b:Number, c:Number, d:Number):Number - { - t = t / d; - if (t < 0.7) { - t *= 1.0 / 0.65; - return c * (t * t) + b; - } - return c * (t * t) + b; - } - - public static function Finish(e:TweenEvent) - { - //_strace("done " + e.currentTarget.obj.x + " " + e.currentTarget.obj.y + " " + e.currentTarget.obj.scaleX + " " + e.currentTarget.obj.scaleY); - e.currentTarget.removeEventListener(TweenEvent.MOTION_FINISH, Finish); - } - public static function Popup(mc, startScale = 0.8, finishCallback = null) - { - var rect:Rectangle = mc.getRect(mc); - var targetX = mc.x; - var targetY = mc.y; - var centerX = mc.x + rect.left + mc.width / 2.0; - var centerY = mc.y + rect.top + mc.height / 2.0; - var startX = centerX - (rect.left + mc.width / 2.0) * startScale; - var startY = centerY - (rect.top + mc.height / 2.0) * startScale; - var tweenSX = new Tween(mc, "scaleX", singleBounceEase, startScale, 1.0, 4, false); - if (finishCallback) tweenSX.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenSY = new Tween(mc, "scaleY", singleBounceEase, startScale, 1.0, 4, false); - if (finishCallback) tweenSY.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenX = new Tween(mc, "x", singleBounceEase, startX, targetX, 4, false); - if (finishCallback) tweenX.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenY = new Tween(mc, "y", singleBounceEase, startY, targetY, 4, false); - if (finishCallback) tweenY.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - return [tweenSX, tweenSY, tweenX, tweenY]; - } - public static function StringSplit(s:String, delim:String, max:int = -1):Array - { - var ret:Array = s.split(delim); - if (max != -1) { - var more:String = ret.slice(max - 1).join(delim); - ret.splice(max - 1); - ret[max - 1] = more; - } - return ret; - } - - public static function StringStartsWith(str:String, substr:String):Boolean - { - if (substr.length > str.length) return false; - return (str.substr(0, substr.length) == substr); - } - - public static function StringEndsWith(str:String, substr:String):Boolean - { - if (substr.length > str.length) return false; - return (str.substr(str.length - substr.length, substr.length) == substr); - } - - public static function StringContains(str:String, substr:String):Boolean - { - return (str.indexOf(substr) !== -1); - } - - private static var vowelsAndH = { - "a":true, "A":true, - "e":true, "E":true, - "i":true, "I":true, - "o":true, "O":true, - "u":true, "U":true, - "h":true, "H":true - } - public static function StringStartsWithVowelOrH(s:String):Boolean - { - if (vowelsAndH[s.charAt(0)]) return true; - return false; - } - - public static function CopyObject(obj, except = null) - { - var i; - if (except == null) except = []; - if (obj is Array) { - var obj2 = []; - for (i = 0; i < obj.length; i++) { - obj2.push(Utils.CopyObject(obj[i])); - } - return obj2; - } - var ret:Object = {}; - for (i in obj) - { - if (except.indexOf(i) == -1) { - ret[i] = obj[i]; - } - } - - return ret; - } - public static function CopyToObject(objFrom, objTo, except = null) - { - if (except == null) except = []; - for (var i in objFrom) - { - if (except.indexOf(i) == -1) { - objTo[i] = objFrom[i]; - } - } - } - public static function CopyToObjectOnly(objFrom, objTo, only) - { - if (only == null) return; - for (var i in only) - { - if (objFrom.hasOwnProperty(only[i])) - { - objTo[only[i]] = objFrom[only[i]]; - } - } - } - - public static function ColorizeRGB(clip:MovieClip, r:int,g:int,b:int) - { - var cTransform = clip.transform.colorTransform; - cTransform.redOffset = r; - cTransform.greenOffset = g; - cTransform.blueOffset = b; - clip.transform.colorTransform = cTransform; - } - - public static function hex2rgb (hex):Object - { - var red = hex>>16; - var greenBlue = hex-(red<<16) - var green = greenBlue>>8; - var blue = greenBlue - (green << 8); - return({r:red, g:green, b:blue}); - } - - public static function RGBtoHEX(r, g, b) { - return r << 16 | g << 8 | b; - } - - /** - * NOTE: An alpha of 1 will make the object a solid color (good for silhouettes) - */ - public static function TintDisplayObject(obj:DisplayObject, color:uint = 0xffffff, alpha:Number = 1.0) - { - var cTint:Color = new Color(); - cTint.setTint(color, alpha); - obj.transform.colorTransform = cTint; - } - - // given an origin (ox, oy) and a look at point (tx, ty), - // and a clip with the given number of rotation states, which - // rotation should we pick? - public static function Rotation(ox, oy, tx, ty, rotations) - { - var delta:Point = new Point(tx - ox, ty - oy); - if (Point.distance(delta, new Point(0.0, 0.0)) < 0.00001) { - delta.y = -1.0; - } - var d = ( - (-Math.floor( - /* calculate the rotation and scale it */ - Math.atan2(delta.y, delta.x) / (Math.PI * 2.0) * rotations - + 0.5 // add 0.5 and take the floor (round to closest int) - ) - + rotations) // atan2 returns in the range -pi to pi, measured ccw from +x, - // we negate it and add rotations again to get it in the range - // [0, rotations] - % rotations) + 1; // add 1 to reference frames - return d; - } - /* performs multiple operations asynchronously, but wait for them all to finish: - * instead of calling a bunch of functions and passing callbacks, pass those callbacks to WaitForFunctions - * and use ret.callbacks[0], ret.callbacks[1], etc... as the callbacks - * this will wait until every command is complete and call all the callbacks at once. - * - * For instance, to load multiple graphics packs asynchronously and wait for them all to finish, - * call var ret = WaitForFunctions([DoneLoading, null, null, null]); to generate - * ret.callbacks[0]..ret.callbacks[3], and pass these to 4 calls to LoadExternalGraphics. - * When these 4 calls complete, the provided 4 functions will be called with the arguments returned - * from the callbacks (in this case, only DoneLoading will be called since the - * other callbacks are null). - */ - public static function WaitForFunctions(...funcs):Object - { - var ret:Object = {}; - // has a callback been hit? - ret.hit = new Array(funcs.length); - // what were the original arguments the callback was called with - ret.args = new Array(funcs.length); - // a list of the artifical callbacks we are providing - ret.callbacks = new Array(funcs.length); - // the real callbacks - ret.funcs = funcs; - ret.done = false; - - ret.immediate = []; - - for (var i = 0; i < funcs.length; i++) { - // we have to setup this temp callback in another function, because the anon function's - // activation object will contain the current scope, meaning that the variable - // i will be updated in each function; if we do it in a seperate function each - // activation object will reference a different i - ret.callbacks[i] = Utils.SetupFunction(ret, i); - } - return ret; - } - - /** - * Returns the standard money format for an integer amount - */ - public static function FormatCurrency(amount:int, symbol:String = "$"):String - { - var afterDecimal:String = (amount % 100).toString(); - while (afterDecimal.length < 2) afterDecimal = "0" + afterDecimal; //mmmm string concatenation - - var beforeDecimal:String; - if (amount > 100) - { - beforeDecimal = Math.floor(amount/100).toString(); - } - else - { - beforeDecimal = "0"; - } - - return symbol + beforeDecimal + "." + afterDecimal; - } - - public static function FormatNumber(amount){ - var whole = Math.floor(amount); - // convert the number to a string - var amount_str:String = String(whole); - var total_str:String = String(amount); - - var number_array:Array = []; - var start:Number; - var end:Number = amount_str.length; - while (end > 0) { - start = Math.max(end - 3, 0); - number_array.unshift(amount_str.slice(start, end)); - end = start; - } - - var point = total_str.indexOf("."); - - var ret = number_array.join(","); - if (point != -1 && point < total_str.length) - { - ret += total_str.substr(point); - } - - return ret; - } - - protected static function SetupFunction(ret, i):Function - { - var a:Function = - function(...rest) { - if (ret.immediate[i]) ret.immediate[i].apply(null, rest); - ret.hit[i] = true; - ret.args[i] = rest; - var ok:Boolean = true; - var j; - for (j = 0; j < ret.hit.length; j++) { - if (!ret.hit[j]) { ok = false; break; } - } - if (ok && !ret.done) { - ret.done = true; - for (j = 0; j < ret.funcs.length; j++) { - if (ret.funcs[j] != null) ret.funcs[j].apply(null, ret.args[j]); - } - } - }; - return a; - } - - // useful for the paned dialogs to show a certain pane/button - public static function OnlyVisible(obj, set:Array, index:int) - { - for (var i in set) { - if (i != index) { - obj[set[i]].visible = false; - } else { - obj[set[i]].visible = true; - } - } - } - public static function AllVisible(obj, set:Array) - { - for (var i in set) { - obj[set[i]].visible = true; - } - } - // set one of a list of tabs to be enabled - public static function OnlyToggled(obj, set:Array, index:int) - { - for (var i in set) { - if (i != index) { - obj[set[i]].SetToggled(false); - } else { - obj[set[i]].SetToggled(true); - } - } - } - // get the frame number of a label in the timeline - public static function GetLabelFrame(mc, name:String):int - { - for (var l in mc.currentLabels) { - if (mc.currentLabels[l].name == name) return mc.currentLabels[l].frame; - } - return 1; - } - // generate a quick text field of a certain color/style - public static function BasicTextField(color:uint, - size:int, - font:String, - text:String, - additional:Object = null, - align = "left"):TextField - { - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.align = align; - if (additional != null) for (var a in additional) f[a] = additional[a]; - f.font = font; - f.color = color; - f.size = size; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.text = text; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - return t; - } - public static function var_dump(_obj, name = "Dump") - { - _strace(name + " " + (_obj) + " {"); - flash.utils.describeType(_obj); - var varList:XMLList = flash.utils.describeType(_obj)..variable; - - for(var i:int; i < varList.length(); i++) - { - //Show the name and the value - _strace(" " + varList[i].@name+' = '+ _obj[varList[i].@name]); - } - _strace("}"); - } - - public static function SetChildFrames(parentClip, frame, exclude = null) - { - if (parentClip is MovieClip && parentClip.name != exclude) - { - parentClip.gotoAndStop(frame); - for (var i = 0; i < parentClip.numChildren; i++) - { - Utils.SetChildFrames(parentClip.getChildAt(i), frame, exclude); - } - } - } - - public static function SetChildFramesNoParent(parentClip, frame, exclude = null) - { - if (parentClip is MovieClip && parentClip.name != exclude) - { - for (var i = 0; i < parentClip.numChildren; i++) - { - Utils.SetChildFrames(parentClip.getChildAt(i), frame, exclude); - } - } - } - - //modifies the array passed as parameter, following the MO of the built in Array.sort() - public static function insertionSort(array:Array, compareFunction:Function):void - { - for(var i:int=1; i < array.length; i++) - { - var value:Object = array[i]; - var k:int=i-1; - while( k >= 0 && compareFunction(array[k], value) == -1) - { - array[k+1]=array[k]; - k--; - } - array[k+1]=value; - } - } - - - public static function Screenshot(sourceClip, receiverURL, filename) - { - - var jpgSource:BitmapData; - - if (sourceClip is Stage) - { - jpgSource = new BitmapData (sourceClip.stageWidth, sourceClip.stageHeight); - } else { - jpgSource = new BitmapData (sourceClip.width, sourceClip.height); - } - - jpgSource.draw(sourceClip); - - var jpgEncoder:JPGEncoder = new JPGEncoder(85); - var jpgStream:ByteArray = jpgEncoder.encode(jpgSource); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - var jpgURLRequest:URLRequest = new URLRequest(receiverURL+"?name="+filename); - jpgURLRequest.requestHeaders.push(header); - jpgURLRequest.method = URLRequestMethod.POST; - jpgURLRequest.data = jpgStream; - navigateToURL(jpgURLRequest, "_blank"); - - } - - - public static function SetColors(clip, color) - { - var colorTransform:ColorTransform; - - if (clip == null || color == null) return; - - if (clip.hasOwnProperty("outline") && clip.outline != null) - { - colorTransform = clip.outline.transform.colorTransform; - colorTransform.color = color.Outline; - clip.outline.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryOutline") && clip.secondaryOutline != null) - { - colorTransform = clip.secondaryOutline.transform.colorTransform; - colorTransform.color = color.LightOutline; - clip.secondaryOutline.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("color") && clip.color != null) - { - colorTransform = clip.color.transform.colorTransform; - colorTransform.color = color.Primary; - clip.color.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryColor") && clip.secondaryColor != null) - { - colorTransform = clip.secondaryColor.transform.colorTransform; - colorTransform.color = color.Secondary; - clip.secondaryColor.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("shadow") && clip.shadow != null) - { - colorTransform = clip.shadow.transform.colorTransform; - colorTransform.color = color.Shadow; - clip.shadow.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryShadow") && clip.secondaryShadow != null) - { - colorTransform = clip.secondaryShadow.transform.colorTransform; - colorTransform.color = color.SecondaryShadow; - clip.secondaryShadow.transform.colorTransform = colorTransform; - } - } - /* returns a rect with the x, and y pos to center and the scaleX and scaleY as width and height */ - public static function GetUniformScaleRect(clip:MovieClip, maxWidth, maxHeight) - { - var rect:Rectangle = new Rectangle(0,0,0,0); - - var widthScale = Math.min(maxWidth / clip.width, 999); - var heightScale = Math.min(maxHeight / clip.height, 999); - - var scale = 1; - if (widthScale > heightScale) - { - scale = heightScale; - } else { - scale = widthScale; - } - - rect.width = clip.width * scale; - rect.height = clip.height * scale; - - var pb = clip.getBounds(clip); - var xadjust = -pb.left * scale; - var yadjust = -pb.top * scale; - - rect.x = xadjust + (maxWidth - rect.width) / 2; - rect.y = yadjust + (maxHeight - rect.height) / 2; - - rect.width = scale; - rect.height = scale; - - return rect; - } - - public static function Dec2Hex(d) - { - var chars:String = "0123456789ABCDEF"; - var str:String = ""; - while (d > 0 || str.length < 2) - { - var digit = d % 16; - d = (d - digit) / 16; - str = chars.charAt(digit) + str; - } - return str; - } - - public static function Hex2Dec(h:String) - { - var chars:String = "0123456789ABCDEF"; - var val = 1; - var res = 0; - for (var i = h.length - 1; i >= 0; i--) - { - res += chars.indexOf(h.substr(i, 1)) * val; - val *= 16; - } - return res; - } - - public static function ShallowCopyArray(array:Array) - { - if (!array) return null; - - var newArray:Array = []; - for (var i:int = 0; i < array.length; i++) - { - newArray.push(array[i]); - } - return newArray; - } - - /* Note: Will fail if any items in either array have reference type semantics (unless they point to the same object) - * (as opposed to value type semantics) - */ - public static function areEqual(a:Array,b:Array):Boolean { - if(a.length != b.length) { - return false; - } - var len:int = a.length; - for(var i:int = 0; i < len; i++) { - if(a[i] !== b[i]) { - return false; - } - } - return true; - } - - /* Note: Will fail if any items in either array have reference type semantics - * (as opposed to value type semantics) - */ - public static function objectsAreEqual(a:Object,b:Object):Boolean { - - for (var i in a) - { - if (!b.hasOwnProperty(i) || a[i] != b[i]) return false; - } - - return true; - } - - public static function DeepCopyClone (source : Object) : * - { - var array : ByteArray = new ByteArray (); - - array.writeObject (source); - array.position = 0; - - return array.readObject (); - } - - // {a:1, b:2} => [1,2] - public static function ObjectValues (obj:Object):Array { - var array = []; - for (var key in obj) array.push(obj[key]); - return array; - } - - // {a:1, b:2} => ["a","b"] - public static function ObjectKeys (obj:Object):Array { - var array = []; - for (var key in obj) array.push(key); - return array; - } - - // normal random variate generator; mean m, standard deviation s - public static function BoxMullerRandomNormal(m:Number, s:Number) : Number - { - var x1, x2, w, y1:Number; - var y2:Number; - var use_last:Boolean = false; - - if (use_last == true) /* use value from previous call */ - { - y1 = y2; - use_last = false; - } - else - { - do { - x1 = 2.0 * Math.random() - 1.0; - x2 = 2.0 * Math.random() - 1.0; - w = x1 * x1 + x2 * x2; - } while ( w >= 1.0 ); - - w = Math.sqrt( (-2.0 * Math.log( w ) ) / w ); - y1 = x1 * w; - y2 = x2 * w; - use_last = true; - } - - return( m + y1 * s ); - } - - public static function SanitizeNumber(n) - { - if (n is Number) - { - if (n == Number.NEGATIVE_INFINITY || n == Number.POSITIVE_INFINITY || n == Number.NaN) return 0; - } - return n; - } - - public static function IsNumberInvalid(n) - { - if (n is Number) - { - if (n == Number.NEGATIVE_INFINITY || n == Number.POSITIVE_INFINITY || n == Number.NaN) return true; - } - return false; - } - - public static function LimitNumberToMax(n) - { - if (n == Number.POSITIVE_INFINITY) return Number.MAX_VALUE; - return n; - } - - /* - value= Math.round(20/7); - value= int((20/7)*10)/10; - value= int((20/7)*100)/100; - value= int((20/7)*1000)/1000; - value= int((20/7)*10000)/10000; - */ - public static function RoundToDecimalPlaces(number:Number, places:int) - { - return Math.round((number)*Math.pow(10,places))/Math.pow(10,places); - } - - public static function GetShuffledArray(a:Array) : Array - { - var r:Array = a.concat(); - r.sort(randomSort); - return r; - } - - ///Convenience function since I keep forgetting the name of randomSort (hint: it's randomSort) - public static function ShuffleArray(a:Array) - { - a.sort(randomSort); - } - - public static function PickRandom(a:Array) - { - return a[Math.floor(Math.random() * a.length)]; - } - - /** - * Returns n elements of array a, up to a maximum of a's length. - * If forceCopy is set, the returned array will always be a new instance. - */ - public static function PickRandomSet(a:Array, n:int, forceCopy:Boolean=false):Array - { - if (a.length <= n || a.length == 0) - { - if (forceCopy) return a.concat(); - else return a; - } - if (n == 1) return [PickRandom(a)]; - - var shuffled:Array = GetShuffledArray(a); - return shuffled.slice(0, n); - } - - /** - * Does not randomly sort an array! To do that, Use the default array.sort with this as its argument. - * If you want a new, shuffled array, use GetShuffledArray - */ - public static function randomSort(a:*, b:*) : Number - { - if (Math.random() < 0.5) return -1; - else return 1; - } - - /** - * Returns the union of arr1 and arr2. If the elements are not primitive types, you'll need to provide a sorting function. - * If inPlace, a1 and a2 will be sorted. - * If they already contain duplicates, then all bets are off. - */ - public static function MergeArrays(arr1:Array, arr2:Array, sortFunc:Function = null, inPlace:Boolean = false) : Array - { - var ret:Array = []; - var a1:Array = (inPlace) ? arr1 : arr1.slice(); - var a2:Array = (inPlace) ? arr2 : arr2.slice(); - - var len1:uint = a1.length; - var len2:uint = a2.length; - var i1:uint = 0; - var i2:uint = 0; - - //Boring cases - if (len1 == 0 && len2 == 0) return ret; - if (len1 == 0) return (inPlace) ? a2.slice() : a2; - if (len2 == 0) return (inPlace) ? a1.slice() : a1; - - if (sortFunc) - { - a1.sort(sortFunc); - a2.sort(sortFunc); - } - else - { - a1.sort(); - a2.sort(); - } - - while (i1 < len1) - { - //add all from a2 up to a1[i1] - while (i2 < len2 && a2[i2] <= a1[i1]) - { - ret.push(a2[i2]); - i2 += 1; - } - if (ret.length == 0 || a1[i1] != ret[ret.length-1]) ret.push(a1[i1]); - i1 += 1; - } - - while (i2 < len2) ret.push(a2[i2]); - - return ret; - } - - public static function ConvertToHHMMSS(seconds:Number):String - { - var s:Number = seconds % 60; - var m:Number = Math.floor((seconds % 3600 ) / 60); - var h:Number = Math.floor(seconds / (60 * 60)); - - var hourStr:String = (h == 0) ? "" : DoubleDigitFormat(h) + ":"; - var minuteStr:String = DoubleDigitFormat(m) + ":"; - var secondsStr:String = DoubleDigitFormat(s); - - return hourStr + minuteStr + secondsStr; - } - - public static function DoubleDigitFormat(num:uint):String - { - if (num < 10) - { - return ("0" + num); - } - return String(num); - } - - public static function CapitolizeString(str:String) : String - { - var firstChar:String = str.substr(0, 1); - var restOfString:String = str.substr(1, str.length); - - return firstChar.toUpperCase()+restOfString.toLowerCase(); - } - - // ^ Nice spelling, goof! - public static function CapitalizeString(str:String) : String - { - return CapitolizeString(str); - } - - public static function GetListString(listStrings:Array) : String - { - var andString:String = "&"; - var count:int = 0; - - var listString:String = ""; - for (var i = 0; i < listStrings.length; i++) - { - if (count > 0 && listStrings.length == 2) listString += " "+andString+" "; // For just 2 items - else if (count == listStrings.length-1 && listStrings.length > 2) - { - // For adding "and" at the end of 3+ items. It is: ", and $(item)" - var endingString:String = ""; - endingString = endingString.replace("$(item)", listStrings[i]); - listString += endingString; - count++; - continue; - } - else if (count > 0) listString += ", "; // Comma separated list - - listString += listStrings[i]; - count++; - } - - return listString; - } - - /* - * Flash doesn't like the way MySQL prints dates (2016-06-02 13:00:00) - * "The year month and day terms can be separated by a forward slash (/) or by spaces, but never by a dash (-)." - */ - public static function ParseDate (dateString:String) : Date - { - var pattern:RegExp = /-/g; - var date = new Date(); - dateString = dateString.replace(pattern, "/"); - date.setTime(Date.parse(dateString)); - return date; - } - - /* - * For display only, not intended to be read by ParseDate - * Tuesday, June 7th, 2016 at 10:32 AM - */ - public static function FormatDate (date:Date) : String - { - var f:DateTimeFormatter = new DateTimeFormatter("en-US"); - var dateStr:String; - var lastChar:String; - - //Flash can't do "1st", "2nd", etc - - f.setDateTimePattern("d"); - dateStr = f.format(date); - lastChar = dateStr.charAt(dateStr.length - 1); - - if (lastChar == "1" && dateStr != "11") dateStr += "st"; - else if (lastChar == "2" && dateStr != "12") dateStr += "nd"; - else if (lastChar == "3" && dateStr != "13") dateStr += "rd"; - else dateStr += "th"; - - f.setDateTimePattern("EEEE, MMMM '" + dateStr + "', yyyy 'at' h:mm a"); - return f.format(date); - } - - /* Simply counts the number of properties on the object - */ - public static function CountObjectParameters(obj:Object):int - { - var cnt:int=0; - - for (var s:String in obj) cnt++; - - return cnt; - } - - /** - * For when shit gets real - */ - public static function PrintStackTrace() - { - try { - throw new Error('StackTrace'); - } catch (e:Error) { - _strace(e.getStackTrace()); - } - } - } -} \ No newline at end of file diff --git a/org/aszip/compression/CompressionMethod.as b/org/aszip/compression/CompressionMethod.as deleted file mode 100644 index 42fe7a0..0000000 --- a/org/aszip/compression/CompressionMethod.as +++ /dev/null @@ -1,17 +0,0 @@ -package org.aszip.compression - -{ - - /** - * The CompressionMethod class lets you choose the compression algorithms used for the files in the ZIP. - */ - public class CompressionMethod - - { - - public static var GZIP:String = 'GZIP'; - public static var NONE:String = 'NONE'; - - } - -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/flash/util/RectangleNode.as b/flash/util/RectangleNode.as new file mode 100644 index 0000000..6f31e44 --- /dev/null +++ b/flash/util/RectangleNode.as @@ -0,0 +1,178 @@ +package util { + import flash.geom.Rectangle; + + public class RectangleNode + { + public var Left:RectangleNode = null; + public var Right:RectangleNode = null; + public var Rect:Rectangle = null; + public var InUse:Boolean = false; + public var Removed:Boolean = false; + public var Parent:RectangleNode = null; + public var AllocationID = 0; + public var Host:RectanglePacker= null; + public var MinAllocationID = 0; + public var NodeID; + public static var NextNodeID = 0; + + public var DontRemove = false; + + public var LastAccessTime = 0; + + public var Flags = []; + + public var UpdateTo:RectangleNode = null; + + /* + public function get Removed() + { + return _Removed; + } + + public function set Removed(r) + { + this._Removed = r; + } + + public function get Host():RectanglePacker + { + return _Host; + } + public function set Host(p:RectanglePacker) + { + this._Host = p; + + if (_Left && _Left.Host != p) + { + throw new Error("bad left host"); + } + if (_Right && _Right.Host != p) + { + throw new Error("bad right host"); + } + if (_Parent && _Parent.Host != p) + { + throw new Error("bad parent host"); + } + + } + + public function get Left():RectangleNode + { + return _Left; + } + public function set Left(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad left host"); + } + _Left = n; + } + public function get Right():RectangleNode + { + return _Right; + } + public function set Right(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad right host"); + } + _Right = n; + } + + public function get Parent():RectangleNode + { + return _Parent; + } + public function set Parent(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad parent host"); + } + _Parent = n; + } + */ + public function get IsFreeSpace() + { + return Left == null && Right == null && !InUse; + } + public function UpdateLinksFromNode(node:RectangleNode) + { + if (node.Parent) + { + if (node.Parent.Left == node) + { + node.Parent.Left = this; + } + if (node.Parent.Right == node) + { + node.Parent.Right = this; + } + } + if (node.Left) + { + node.Left.Parent = this; + } + if (node.Right) + { + node.Right.Parent = this; + } + } + public function MakeFromNode(node:RectangleNode) + { + //_Host = node.Host; + Host = node.Host; + Left = node.Left; + Right = node.Right; + Parent = node.Parent; + AllocationID = node.AllocationID; + InUse = node.InUse; + MinAllocationID = node.MinAllocationID; + NodeID = node.NodeID; + Rect = node.Rect.clone(); + Removed = node.Removed; + DontRemove = node.DontRemove; + } + public function RectangleNode(x, y, w, h, host:RectanglePacker) + { + this.NodeID = NextNodeID++; + this.Host = host; + this.Rect = new Rectangle(x, y, w, h); + } + public function OutputJSON() + { + var node = {}; + node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; + node.in_use = InUse; + node.id = NodeID; + if (this.Left) node.left = this.Left.OutputJSON(); + if (this.Right) node.right = this.Right.OutputJSON(); + return node; + } + + public function ReadJSON(details) + { + details.new_node = this; + this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); + this.Removed = false; + + this.InUse = details.in_use; + + if (details.hasOwnProperty("right")) + { + this.Right = new RectangleNode(0, 0, 0, 0, this.Host); + Right.ReadJSON(details.right); + Right.Parent = this; + } + if (details.hasOwnProperty("left")) + { + this.Left = new RectangleNode(0, 0, 0, 0, this.Host); + Left.ReadJSON(details.left); + Left.Parent = this; + } + } + } +} diff --git a/flash/util/RectanglePacker.as b/flash/util/RectanglePacker.as new file mode 100644 index 0000000..597d7fd --- /dev/null +++ b/flash/util/RectanglePacker.as @@ -0,0 +1,562 @@ +package util { + import flash.geom.*; + import flash.display.BitmapData; + import flash.display.MovieClip; + import flash.text.TextField; + import flash.events.*; + import flash.sampler.StackFrame; + + public class RectanglePacker + { + protected var w:int; + protected var h:int; + protected var root:RectangleNode; + public var NextAllocationID = 0; + + public function get width():int { return w; } + public function get height():int { return h; } + + public function RectanglePacker(w, h) + { + this.w = w; + this.h = h; + root = new RectangleNode(0, 0, w, h, this); + root.AllocationID = -1; + } + protected var area = 0; + + protected var testRender:MovieClip = new MovieClip(); + + public function GetRoot():RectangleNode + { + return root; + } + + public function GetLeafNodes():Array + { + return GetLeafNodesInternal(root); + } + + protected function GetLeafNodesInternal(n:RectangleNode):Array + { + if (n.InUse) return [n]; + var ret:Array = new Array(); + if (n.Left) ret = GetLeafNodesInternal(n.Left); + if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); + return ret; + } + + public function GetUsedArea() + { + return area; + } + + public function get efficiency() + { + return area / (w * h); + } + + protected function RectCost(w, h) + { + if (w == 0 || h == 0) return 99999999; + return (Math.max(w, h) / Math.min(w, h)) * w * h; + } + + protected function EnumerateTree(r:RectangleNode = null, indent = "") + { + if (r == null) r = this.root; + var str = ""; + str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; + if (r.Left) str += EnumerateTree(r.Left, indent + " "); + if (r.Right) str += EnumerateTree(r.Left, indent + " "); + return str; + } + + /* + * Remove a list of nodes from the tree. + * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree + * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, + leaving the original objects intact (in case something still references them) + */ + public function RemoveNodes(nodes:Array, fullyDestroy = true) + { + + /* DEBUG CHECKS */ + /* + this.PerformDebugCheck(); + + var str = ""; + for (var i = 0; i < nodes.length; i++) + { + str += nodes[i].NodeID + "\n"; + } + + var orig = nodes.concat(); + + var strs = [str, EnumerateTree()]; + + RenderDetailsBox.StartTrack("PackRemoveTime"); + + for (var i = 0; i < nodes.length; i++) + { + var n:RectangleNode = nodes[i]; + if (n.Host != this) + { + throw new Error("bad host!"); + } + } + */ + /* END DEBUG CHECKS */ + + var i, n:RectangleNode, p:RectangleNode; + + // setup the Removed flag on every node that should be removed + // we also check at this time to see if any more nodes need to be removed, such as a parent of + // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + if (n.Host == this) + { + n.Removed = true; + + if (n.InUse) + { + // sum up the total removed area + area -= n.Rect.width * n.Rect.height; + } + + if (n.Parent != null) + { + p = n.Parent; + // check and see if the current node's parent still has any valid children + if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) + { + // all of the current nodes siblings are either being removed or are blank, so + // we can remove the parent too + if (p.Left.IsFreeSpace) + { + // the left child was empty space before, so we can remove it (if it wasn't + // empty space it is already being removed so it doesn't need to be added + // to the list) + if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); + } + if (p.Right.IsFreeSpace) + { + // the right child was empty space before, so we can remove it + if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); + } + if (p != root && nodes.indexOf(p) == -1) + { + // remove the parent node too (provided it isn't the root!) + nodes.push(p); + } + } + } + } + } + + // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, + // so go ahead and remove them + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + + if (n.Parent != null) + { + // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not + // also getting removed!) + p = n.Parent; + + if (!p.Removed) + { + if (p.Left && p.Right) + { + var newNode:RectangleNode; + if (p.Left.Removed && p.Right.Removed) + { + // both children were removed, but the parent wasn't, so the parent must be root + // (since we never remove the root) + if (p != root) + { + throw new Error("should be root"); + } + p.Left.Parent = null; + p.Right.Parent = null; + p.Left = null; + p.Right = null; + p.InUse = false; + } else if (!p.Left.Removed) { + // Right node removed, Left node not removed + if (!p.Left.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Right); + newNode.UpdateLinksFromNode(p.Right); + } + // Left node is used + p.Right.InUse = false; + p.Right.Left = null; + p.Right.Right = null; + p.Right.Removed = false; + } else { + throw new Error("should have been caught above!"); + } + } else { + // Left node removed, Right node not removed + if (!p.Right.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Left); + newNode.UpdateLinksFromNode(p.Left); + } + // Left node is used + //p.Left.Removed = true; + p.Left.InUse = false; + p.Left.Left = null; + p.Left.Right = null; + p.Left.Removed = false; + //p.Left.Parent = null; + } else { + throw new Error("should have been caught above!"); + } + } + } else { + // huh? how does n.Parent == p but p has no children? something went wrong + throw new Error("shouldn't have gotten here"); + } + } + } + //strs.push(EnumerateTree()); + } + } + + public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode + { + + var node:RectangleNode = FindSizedNode(w, h, root); + + if (node == null) + { + //UHOH, texture full + return null; + } + area += w * h; + node.InUse = true; + + var splitVertFirstCost = 0; + if (w < node.Rect.width) + { + splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); + } + + var splitHorizFirstCost = 0; + if (h < node.Rect.height) + { + splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); + } + + + + if (splitVertFirstCost <= splitHorizFirstCost) + { + node.Flags.push("SplitVertFirst"); + if (w < node.Rect.width) + { + node.Flags.push("SplitVert"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + if (h < node.Rect.height) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + } else { + node.Flags.push("SplitHorzFirst"); + if (h < node.Rect.height) + { + node.Flags.push("SplitVert"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + if (w < node.Rect.width) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + } + NextAllocationID++; + if (useInstead) + { + useInstead.MakeFromNode(node); + useInstead.UpdateLinksFromNode(node); + useInstead.Flags = node.Flags; + node = useInstead; + node.Flags.push("UseInstead"); + } + + //if (!CheckOKNode(node)) node.Flags.push("BadNode"); + + return node; + } + public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) + { + if (r == null) r = this.root; + if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) + { + var ancestor:RectangleNode = FindCommonNode(n, r); + throw new Error("bad node allocated!"); + return false; + } + var ok = true; + if (r.Left) ok = ok && CheckOKNode(n, r.Left); + if (r.Right) ok = ok && CheckOKNode(n, r.Right); + return ok; + } + + public function PerformDebugCheck() + { + DebugInternal(this.root); + } + + protected function DebugInternal(n:RectangleNode) + { + if (n.Host != this) + { + throw new Error("problem with host!"); + } + if (n.IsFreeSpace) + { + if (n.Left || n.Right) + { + throw new Error("shouldn't have children"); + } + } + if ((n.Left && !n.Right) || (n.Right && !n.Left)) + { + throw new Error("mismatched children"); + } + if (n.Left && n.Left.Parent != n) + { + throw new Error("left child has bad parent"); + } + if (n.Right && n.Right.Parent != n) + { + throw new Error("right child has bad parent"); + } + if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) + { + throw new Error("problem with parent"); + } + if (n.Left) DebugInternal(n.Left); + if (n.Right) DebugInternal(n.Right); + } + + public function FindCommonNode(a:RectangleNode, b:RectangleNode) + { + var aHistory = []; + var bHistory = []; + while (a != null) + { + aHistory.push(a); + a = a.Parent; + } + while (b != null) + { + bHistory.push(b); + b = b.Parent; + } + var i = aHistory.length - 1; + var j = bHistory.length - 1; + var same = null; + while (i >= 0 && j >= 0) + { + if (aHistory[i] == bHistory[j]) + { + same = aHistory[i]; + } else { + break; + } + i--; + j--; + } + return same; + } + + public function TestRender() + { + while (testRender.numChildren > 0) + { + testRender.removeChildAt(0); + } + testRender.graphics.clear(); + TestRenderNode(root, testRender); + return testRender; + } + protected function TestRenderNode(n:RectangleNode, m:MovieClip) + { + var g:MovieClip = new MovieClip(); + m.addChild(g); + g.graphics.lineStyle(1, 0, 1); + if (n.Left != null) TestRenderNode(n.Left, m); + if (n.Left != null) TestRenderNode(n.Right, m); + if (n.InUse) + { + g.graphics.beginFill(0xFFFF00, 0.2); + } + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + if (n.InUse) + { + g.graphics.endFill(); + var t:TextField = new TextField(); + t.text = n.NodeID; + t.x = n.Rect.x + n.Rect.width / 2.0; + t.y = n.Rect.y + n.Rect.height / 2.0; + g.addChild(t); + g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); + g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); + } + + } + public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) + { + if (n.InUse) + { + //_trace(Math.round(n.LastAccessTime / 1000)); + } + var p:RectangleNode = n.Parent; + if (p) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); + g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); + g.graphics.endFill(); + t.text = p.NodeID; + if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); + g.oldListener = function(e){MouseOver(p, g, t);}; + g.addEventListener(MouseEvent.CLICK, g.oldListener); + } + } + public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(0xFFFF00, 0.2); + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + g.graphics.endFill(); + t.text = n.NodeID; + } + protected function SplitVert(node:RectangleNode, leftWidth) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function SplitHoriz(node:RectangleNode, topHeight) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode + { + if (node.InUse) return null; + if (node.Rect.width >= w && node.Rect.height >= h) + { + if (node.Left != null && node.Right != null) + { + var t:RectangleNode = FindSizedNode(w, h, node.Left); + if (t != null) return t; + t = FindSizedNode(w, h, node.Right); + return t; + } else { + return node; + } + } + return null; + } + + public function LoadTree(details) + { + this.root = new RectangleNode(0, 0, 0, 0, this); + root.ReadJSON(details); + + this.NextAllocationID = 0; + this.area = 0; + + var queue:Array = new Array(); + queue.push(root); + while (queue.length > 0) + { + var node:RectangleNode = queue.shift(); + node.AllocationID = NextAllocationID; + node.MinAllocationID = NextAllocationID; + if (node.Left) queue.push(node.Left); + if (node.Right) queue.push(node.Right); + if (node.InUse) this.area += node.Rect.width * node.Rect.height; + } + NextAllocationID++; + } + + public function GetNodePath(node:RectangleNode) + { + var output:String = ""; + while (node != this.root) + { + output = (node == node.Parent.Left ? "l" : "r") + output; + node = node.Parent; + } + return output; + } + + public function GetNodeFromPath(path:String):RectangleNode + { + var node:RectangleNode = this.root; + for (var i = 0; i < path.length; i++) + { + if (!node) return null; + if (path.charAt(i) == "r") + { + node = node.Right; + } else { + node = node.Left; + } + } + return node; + } + } +} diff --git a/flash/util/Utils.as b/flash/util/Utils.as new file mode 100644 index 0000000..f792003 --- /dev/null +++ b/flash/util/Utils.as @@ -0,0 +1,389 @@ +package util +{ + import flash.display.*; + import flash.geom.*; + public class Utils + { + public static function GetChildren(clip:MovieClip):Array + { + var ret:Array = []; + for (var i = 0; i < clip.numChildren; i++) + { + ret.push(clip.getChildAt(i)); + } + return ret; + } + + /* + * angle difference + * (range -Math.PI to Math.PI) + */ + public static function GetAngleDiff(a, b) + { + var angleDiff = b - a; + + while (angleDiff > Math.PI) + { + angleDiff -= Math.PI * 2; + } + while (angleDiff < -Math.PI) + { + angleDiff += Math.PI * 2; + } + return angleDiff; + } + + /* + * angle difference + * (range 0 to Math.PI) + */ + public static function GetAngleDiffAbs(a, b) + { + var angleDiff = GetAngleDiff(a, b); + while (angleDiff < 0) + { + angleDiff += Math.PI * 2; + } + + if (angleDiff > Math.PI) + { + angleDiff = Math.PI * 2 - angleDiff; + } + + return angleDiff; + } + + public static function GetTransform(from:Matrix, to:Matrix) + { + var i:Matrix = from.clone(); + i.invert(); + var m:Matrix = to.clone(); + m.concat(i); + return m; + } + + public static function Decompose(m:Matrix) + { + var s:Point = ScaleFromMat(m); + m = m.clone(); + + var sxUnit = s.x >= 0 ? 1 : -1; + var syUnit = s.y >= 0 ? 1 : -1; + + m.scale(sxUnit, syUnit); + + //m.a /= sxUnit; + //m.d /= syUnit; + var rot = RotFromMat(m); + return {sx:s.x, sy:s.y, rot:rot}; + } + + public static function RotFromMat(m:Matrix) + { + return Math.atan2(-m.c, m.a); + } + + public static function ScaleFromMat(m:Matrix):Point + { + var xAxisX = m.a; + var xAxisY = m.c; + + var yAxisX = m.b; + var yAxisY = m.d; + + var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); + if (m.a < 0) sx *= -1; + + var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); + if (m.d < 0) sy *= -1; + + return new Point(sx, sy); + } + + public static function TransformRect(r:Rectangle, m:Matrix) + { + var p1:Point = new Point(r.left, r.top); + var p2:Point = new Point(r.right, r.top); + var p3:Point = new Point(r.left, r.bottom); + var p4:Point = new Point(r.right, r.bottom); + + p1 = m.transformPoint(p1); + p2 = m.transformPoint(p2); + p3 = m.transformPoint(p3); + p4 = m.transformPoint(p4); + + r.left = Math.min(p1.x, p2.x, p3.x, p4.x); + r.top = Math.min(p1.y, p2.y, p3.y, p4.y); + r.right = Math.max(p1.x, p2.x, p3.x, p4.x); + r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); + } + + public static function RoundRect(r:Rectangle) + { + r.left = Math.floor(r.left); + r.top = Math.floor(r.top); + r.right = Math.ceil(r.right); + r.bottom = Math.ceil(r.bottom); + } + + public static function ScaleRect(r:Rectangle, s) + { + r.left *= s; + r.top *= s; + r.right *= s; + r.bottom *= s; + } + + public static function RecursivelyStop(clip) + { + if (clip is MovieClip) + { + clip.stop(); + } + if (clip is DisplayObjectContainer) + { + for (var i = 0; i < clip.numChildren; i++) + { + RecursivelyStop(clip.getChildAt(i)); + } + } + } + + public static function WeirdGotoFrame(clip:MovieClip, frame) + { + var dir = clip.currentFrame > frame ? -1 : 1; + while (clip.currentFrame != frame) + { + RecurseDir(clip, dir); + } + } + + protected static function RecurseDir(clip:MovieClip, dir) + { + for (var i = 0; i < clip.numChildren; i++) + { + var child = clip.getChildAt(i); + if (child is MovieClip) + { + RecurseDir(child, dir); + } + } + if (dir == 1) + { + clip.nextFrame(); + } else { + clip.prevFrame(); + } + } + + protected static var tempSpace:BitmapData = null; + protected static var tempSpaceRect:Rectangle = new Rectangle(); + protected static var tempSpaceMatrix:Matrix = new Matrix(); + protected static var tempSpaceZero:Point = new Point(); + protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); + protected static var lastDrawOffset:Point = new Point(); + public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle + { + if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); + + var oldPad = 0; + var padAmount = 5; + + var ret:Rectangle = new Rectangle(); + + var baseBounds:Rectangle = clip.getBounds(clip); + + var boundsClip:DisplayObject = null; + if (clip is DisplayObjectContainer) + { + boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); + } + + if (boundsClip != null) + { + baseBounds = boundsClip.getBounds(clip); + } + + if (useMatrix) + { + TransformAABBRect(baseBounds, useMatrix); + } + + if (boundsClip != null) + { + return baseBounds; + } + + var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); + var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); + if (tempSpace == null) + { + tempSpace = new BitmapData(minW, minH, true, 0x0); + } + if (tempSpace.width < minW || tempSpace.height < minH) + { + tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); + } + + var r:Rectangle = new Rectangle(); + + baseBounds.left = Math.floor(baseBounds.left); + baseBounds.right = Math.ceil(baseBounds.right); + + baseBounds.top = Math.floor(baseBounds.top); + baseBounds.bottom = Math.ceil(baseBounds.bottom); + + var i; + + var needsChecking = true; + while (needsChecking) + { + needsChecking = false; + r.left = baseBounds.left - padAmount; + r.right = baseBounds.right + padAmount; + + r.top = baseBounds.top - padAmount; + r.bottom = baseBounds.bottom + padAmount; + + ret = r.clone(); + + tempSpaceRect.x = tempSpaceRect.y = 0; + tempSpaceRect.width = tempSpace.width; + tempSpaceRect.height = tempSpace.height; + tempSpace.fillRect(tempSpaceRect, 0x0); + + tempSpaceMatrix.identity(); + if (useMatrix) + { + tempSpaceMatrix.a = useMatrix.a; + tempSpaceMatrix.b = useMatrix.b; + tempSpaceMatrix.c = useMatrix.c; + tempSpaceMatrix.d = useMatrix.d; + tempSpaceMatrix.tx = useMatrix.tx; + tempSpaceMatrix.ty = useMatrix.ty; + } + tempSpaceMatrix.translate(-r.left, -r.top); + + lastDrawOffset.x = -r.left; + lastDrawOffset.y = -r.top; + tempSpace.draw(clip, tempSpaceMatrix); + + tempSpaceRect.width = 1; + tempSpaceRect.height = r.height; + + var sideMovedIn = 0; + for (i = 0; i < r.width; i++) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.left++; + sideMovedIn++; + } + } + if (ret.left < baseBounds.left - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.width - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.right--; + } + } + if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + sideMovedIn = 0; + tempSpaceRect.width = r.width; + tempSpaceRect.height = 1; + tempSpaceRect.x = 0; + for (i = 0; i < r.height; i++) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.top++; + sideMovedIn++; + } + } + if (ret.top < baseBounds.top - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.height - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.bottom--; + } + } + if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + } + return ret; + } + + public static function TransformAABBRect(r:Rectangle, m:Matrix) + { + var o1X = r.left; + var o1Y = r.top; + + var o2X = r.right; + var o2Y = r.top; + + var o3X = r.left; + var o3Y = r.bottom; + + var o4X = r.right; + var o4Y = r.bottom; + + var n1X = o1X * m.a + o1Y * m.c + m.tx; + var n1Y = o1X * m.b + o1Y * m.d + m.ty; + + var n2X = o2X * m.a + o2Y * m.c + m.tx; + var n2Y = o2X * m.b + o2Y * m.d + m.ty; + + var n3X = o3X * m.a + o3Y * m.c + m.tx; + var n3Y = o3X * m.b + o3Y * m.d + m.ty; + + var n4X = o4X * m.a + o4Y * m.c + m.tx; + var n4Y = o4X * m.b + o4Y * m.d + m.ty; + + r.left = Math.min(n1X, n2X, n3X, n4X); + r.right = Math.max(n1X, n2X, n3X, n4X); + + r.top = Math.min(n1Y, n2Y, n3Y, n4Y); + r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); + } + } +} diff --git a/job.py b/job.py index 989c991..77c09e8 100644 --- a/job.py +++ b/job.py @@ -3,6 +3,7 @@ import json from validate import * from args import * +import copy asset_src_schema = { "type":"object", @@ -69,19 +70,24 @@ base_path = os.path.join(self.out_dir, self.rel_path) if not os.path.exists(base_path): os.makedirs(base_path) + resource_names = [] for i,r in enumerate(resources): - path = os.path.join(base_path, "%s_%04d.png" % (self.name, i)) + resource_name = "%s_%04d.png" % (self.name, i) if len(resources) > 1 else self.name + ".png" + resource_names.append(resource_name) + path = os.path.join(base_path, resource_name) with open(path, "wb") as f: f.write(base64.b64decode(r)) if len(data) == 1: graphic_and_asset = {} (name, graphic_data) = data.items()[0] - graphic_and_asset = {"data":graphic_data} + graphic_and_asset = {"data":graphic_data, "resources":resource_names} with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps(graphic_and_asset)) else: + write_data = copy.deepcopy(data) + write_data["resources"] = resource_names with open(os.path.join(base_path, self.name + ".asset"), "w") as f: - f.write(pretty_dumps(data)) + f.write(pretty_dumps(write_data)) for name,details in data.iteritems(): with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps({"data":self.name + ".asset"})) diff --git a/old/Checkbox.as b/old/Checkbox.as deleted file mode 100644 index c5aaba2..0000000 --- a/old/Checkbox.as +++ /dev/null @@ -1,42 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - - public class Checkbox extends MovieClip - { - public var Enabled:Boolean = true; - public function Checkbox() - { - checkbox.gotoAndStop(1); - checkbox.addEventListener(MouseEvent.CLICK, Clicked); - } - - protected function Clicked(event) - { - if (!Enabled) return; - Toggle(); - if (OnClick != null) OnClick(OnClickParam); - } - - protected var checked = false; - public function set Checked(value) { checked = value; checkbox.gotoAndStop(checked ? 2 : 1); } - public function get Checked() { return checked; } - - public function set Text(value) { text.text = value; } - - public var OnClickParam; - public var OnClick; - - - public function Toggle() - { - checked = !checked; - checkbox.gotoAndStop(checked ? 2 : 1); - - - } - - } - -} diff --git a/old/GraphicExport-app.xml b/old/GraphicExport-app.xml deleted file mode 100644 index 5144634..0000000 --- a/old/GraphicExport-app.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - GraphicExport - 1.0 - GraphicExport - - GraphicExport - - - GraphicExport.swf - standard - false - true - false - portrait - auto - true - true - true - - - false - false - desktop extendedDesktop diff --git a/old/GraphicExport.exe b/old/GraphicExport.exe deleted file mode 100644 index 56315aa..0000000 --- a/old/GraphicExport.exe +++ /dev/null Binary files differ diff --git a/old/GraphicExport.fla b/old/GraphicExport.fla deleted file mode 100644 index 0b78ed7..0000000 --- a/old/GraphicExport.fla +++ /dev/null Binary files differ diff --git a/old/GraphicExport.swf b/old/GraphicExport.swf deleted file mode 100644 index 542db97..0000000 --- a/old/GraphicExport.swf +++ /dev/null Binary files differ diff --git a/old/NewGraphicDialog.as b/old/NewGraphicDialog.as deleted file mode 100644 index 152011c..0000000 --- a/old/NewGraphicDialog.as +++ /dev/null @@ -1,224 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - import flash.events.*; - import flash.filesystem.File; - import flash.net.FileFilter; - import Defs.GraphicDef; - import flash.text.engine.GraphicElement; - - public class NewGraphicDialog extends MovieClip - { - - public function NewGraphicDialog() - { - // constructor code - Init(); - } - - var typeButtons:Array = new Array(); - - public function Init() - { - graphicPath.text = "Path to Graphic Here"; - - this.removeChild(browseButton); - - var newBrowseButton = new UI_GenericBlueButton(); - newBrowseButton.Text = "Browse"; - newBrowseButton.OnClick = BrowseForFile; - newBrowseButton.x = browseButton.x + (newBrowseButton.width / 2); - newBrowseButton.y = browseButton.y + (newBrowseButton.height / 2); - addChild(newBrowseButton); - - var newTestButton = new UI_GenericBlueButton(); - newTestButton.Text = "Export"; - newTestButton.OnClick = TestFile; - newTestButton.x = testButton.x + (newTestButton.width / 2); - newTestButton.y = testButton.y + (newTestButton.height / 2); - addChild(newTestButton); - - this.removeChild(typePlaceholderButton); - - var typeX = typePlaceholderButton.x; - var typeY = typePlaceholderButton.y + (typePlaceholderButton.height / 2); - - - var typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Graphic (1)"; - typeButton.OnClick = function(){ SetType(1); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Skeletal (3)"; - typeButton.OnClick = function(){ SetType(3); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Scene (6)"; - typeButton.OnClick = function(){ SetType(6); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - animationCheckbox.Checked = true; - //browseButton - //typePlaceholderButton - //usesInput - //usesText.text = "" - } - - var usesInputDefaultText = "Comma Seperated List of Uses Here"; - - public static var fakeID = 9999999; - public function TestFile() - { - fakeID++; - var graphicName = graphicPath.text; - var graphicData = {id:fakeID,graphic:graphicPath.text,v:1,fs:0,p:0,type:selectedType}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new GraphicDef(graphicData); - - this.Hide(); - graphicExport.ExportItem(graphicDef); - } - - var selectedType = 1; - public function SetType(type:Number) - { - selectedType = type; - - for(var i = 0; i < typeButtons.length; i++) - { - typeButtons[i].Enabled = true; - } - - animationCheckbox.visible = false; - - switch(type) - { - case 1: { - typeButtons[0].Enabled = false; - animationCheckbox.visible = true; - break; - } - case 3: typeButtons[1].Enabled = false; break; - case 6: typeButtons[2].Enabled = false; break; - } - } - - var graphicExport:GraphicExport; - public function Show(parentClip) - { - this.graphicExport = parentClip; - - parentClip.addChild(this); - - SetType(selectedType); - - var graphicList = GameData.Instance().GraphicDefines; - - var usesString:String = ""; - var uniqueUseTypes:Array = new Array(); - for (var i = 0; i < graphicList.length; i++) - { - var graphicDef:GraphicDef = graphicList[i]; - var uses = graphicDef.ExportParams['uses']; - for (var usage in uses) - { - if (uniqueUseTypes[uses[usage]] == null) - { - uniqueUseTypes[uses[usage]] = uses[usage]; - usesString += uses[usage] + ", "; - } - } - } - - graphicPath.text = ""; - - } - - public function CloseClicked(event) - { - Hide(); - } - - public function Hide() - { - if (this.parent != null) this.parent.removeChild(this); - } - - public function BrowseForFile() - { - var file:File = new File(); - var swfTypeFilter:FileFilter = new FileFilter("SWF Files","*.swf"); - file.addEventListener(Event.SELECT, openFile); - file.browse([swfTypeFilter]); - } - - private function openFile(event:Event):void - { - _strace(event.target.nativePath); - var path:String = event.target.nativePath; - var pathParts:Array = path.split("Graphics\\"); - if (pathParts.length == 2) - { - var fileRemainder:String = pathParts[1]; - var withoutExtension:String = fileRemainder.split(".")[0]; - var pattern:RegExp = /\\/g; - withoutExtension = withoutExtension.replace(pattern, "/"); - _strace(withoutExtension); - graphicPath.text = withoutExtension; - - if (withoutExtension.indexOf("Backgrounds") > -1) - { - SetType(6); - } - - if (withoutExtension.indexOf("Monsters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Characters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Portraits") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Quest") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Equipment") > -1) - { - SetType(1); - } - - - } - } - - - } - -} diff --git a/old/PNGExportHelper.as b/old/PNGExportHelper.as deleted file mode 100644 index f8c4c9d..0000000 --- a/old/PNGExportHelper.as +++ /dev/null @@ -1,253 +0,0 @@ -package -{ - import flash.display.*; - import com.adobe.images.*; - import flash.utils.*; - import flash.net.*; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import flash.geom.Point; - - public class PNGExportHelper - { - public static var UseExpandedBitmaps = false; - public static var AlphaThreshold = 5; - - private static function ExpandBitmapBorders(bd:BitmapData, bgColor = 0x0, passes = 1):BitmapData - { - /* - var thresh:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - thresh.threshold(bd, bd.rect, new Point(), "<", (20 << 24), bgColor, 0xFF000000, true); - */ - var sampled:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - bd.lock(); - sampled.lock(); - - for (var y = 0; y < bd.height; y++) - { - for (var x = 0; x < bd.width; x++) - { - var oldVal:uint = bd.getPixel32(x, y); - var a:uint = (oldVal & 0xFF000000) >>> 24; - var rgb:uint = (oldVal & 0xFFFFFF); - if (a > AlphaThreshold) - { - sampled.setPixel32(x, y, (0xFF << 24) | rgb); - } - else - { - sampled.setPixel32(x, y, bgColor); - } - } - } - sampled.unlock(); - bd.unlock(); - - return ExpandBitmapBordersInternal(sampled, bgColor, passes); - } - - private static function ExpandBitmapBordersInternal(bd:BitmapData, bgColor, passes):BitmapData - { - var output:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - - var scale = 16; - var scaled:BitmapData = new BitmapData(bd.width/scale, bd.height/scale, true, bgColor); - var mat:Matrix = new Matrix(); - mat.scale(1/scale, 1/scale); - scaled.draw(bd, mat, null, null, null, true); - - output.lock(); - - var colors:Array = new Array(); - var weights:Array = new Array(); - - for (var oy = 0; oy < scaled.height; oy++) - { - - for (var ox = 0; ox < scaled.width; ox++) - { - - var scaledVal:uint = scaled.getPixel32(ox, oy); - var scaleda:uint = (scaledVal & 0xFF000000) >>> 24; - if (scaleda == 0 || scaleda == 255) - { - output.copyPixels(bd, new Rectangle(ox * scale, oy * scale, scale, scale), new Point(ox * scale, oy * scale)); - continue; - } else { - //_strace(scaleda+""); - } - - - for (var y = oy * scale; y < oy * scale + scale; y++) - { - for (var x = ox * scale; x < ox * scale + scale; x++) - { - var oldVal:uint = bd.getPixel32(x, y); - var a:uint = (oldVal & 0xFF000000) >>> 24; - var rgb:uint = (oldVal & 0xFFFFFF); - - if (a == 0 && rgb == bgColor) - { - colors.length = 0; - weights.length = 0; - - for (var y1 = y - 2; y1 <= y + 2; y1++) - { - for (var x1 = x - 2; x1 <= x + 2; x1++) - { - var dist = Math.abs(x1 - x) + Math.abs(y1 - y); - if (dist >= 3) continue; - - if (x1 >= 0 && x1 < bd.width && y1 >= 0 && y1 < bd.height) - { - colors.push(bd.getPixel(x1, y1)); - weights.push(1 - dist * 0.2); - } - } - } - - var newVal = AveragePixels(colors, weights, bgColor); - if (newVal == null) - { - newVal = oldVal; - } - else - { - var newR:uint = (newVal & 0xFF0000) >> 16; - var newG:uint = (newVal & 0xFF00) >> 8; - var newB:uint = (newVal & 0xFF); - - if (newVal != 0 && colors.length >= 4) - { - var bp = true; - } - - var sorted = colors.sort(function(a, b) - { - var aR:uint = (a & 0xFF0000) >> 16; - var aG:uint = (a & 0xFF00) >> 8; - var aB:uint = (a & 0xFF); - - var bR:uint = (b & 0xFF0000) >> 16; - var bG:uint = (b & 0xFF00) >> 8; - var bB:uint = (b & 0xFF); - - var diffA = Math.abs(aR - newR) + Math.abs(aG - newG) + Math.abs(aB - newB); - var diffB = Math.abs(bR - newR) + Math.abs(bG - newG) + Math.abs(bB - newB); - - return diffA - diffB; - - }, Array.RETURNINDEXEDARRAY | Array.DESCENDING); - - var toRemove = Math.min(2, colors.length - 4); - var removed = 0; - for (var i = 0; i < colors.length; i++) - { - var index = sorted.indexOf(i + removed); - if (index < toRemove) - { - colors.splice(i, 1); - weights.splice(i, 1); - removed++; - i--; - if (removed == toRemove) break; - } - } - - var fixOutliersVal = AveragePixels(colors, weights, bgColor); - if (fixOutliersVal == null) newVal = (0xFF << 24) | newVal; - - newVal = (0xFF << 24) | fixOutliersVal; - } - - output.setPixel32(x, y, newVal); - } - else - { - output.setPixel32(x, y, oldVal); - } - } - } - }//end outer scaled x - }//End outer scaled y - - bd.unlock(); - output.unlock(); - - passes--; - if (passes > 0) - { - return ExpandBitmapBordersInternal(output, bgColor, passes); - } - else - { - return output; - } - } - - private static function AveragePixels(colors:Array, weights:Array, bgColor:uint):uint - { - var rTotal = 0; - var gTotal = 0; - var bTotal = 0; - - var wTotal = 0; - - for (var i = 0; i < colors.length; i++) - { - var color:uint = colors[i]; - var a:uint = (color & 0xFF000000) >>> 24; - var rgb:uint = (color & 0xFFFFFF); - - if (a == 0 && rgb == bgColor) - { - colors.splice(i, 1); - weights.splice(i, 1); - i--; - continue; - } - - var r:uint = (rgb & 0xFF0000) >>> 16; - var g:uint = (rgb & 0xFF00) >>> 8; - var b:uint = (rgb & 0xFF); - var w = weights[i]; - - rTotal += w * r; - gTotal += w * g; - bTotal += w * b; - - wTotal += w; - } - - if (wTotal == 0) - { - return null; - } - - rTotal /= wTotal; - gTotal /= wTotal; - bTotal /= wTotal; - - var rFinal = Math.max(0, Math.min(255, Math.round(rTotal))); - var gFinal = Math.max(0, Math.min(255, Math.round(gTotal))); - var bFinal = Math.max(0, Math.min(255, Math.round(bTotal))); - - return (uint(rFinal) << 16) | (uint(gFinal) << 8) | (uint(bFinal)); - } - - - - public static function GetExportPNG(bd:BitmapData):ByteArray - { - if (!UseExpandedBitmaps) return PNGEncoder.encode(bd); - - var expanded:BitmapData = ExpandBitmapBorders(bd, 0x0, 2); - - //var fr:FileReference = new FileReference(); - //fr.save(PNGEncoder.encode(expanded), "output.png"); - - return PNGEncoderWithAlpha.encode(expanded, bd); - } - - } -} \ No newline at end of file diff --git a/old/PreviewHolder.as b/old/PreviewHolder.as deleted file mode 100644 index 587bf68..0000000 --- a/old/PreviewHolder.as +++ /dev/null @@ -1,57 +0,0 @@ -package { - import flash.display.MovieClip; - - public class PreviewHolder extends MovieClip - { - - var startingWidth = 1024; - var startingHeight = 1024; - - public function PreviewHolder() - { - startingWidth = this.width; - startingHeight = this.height; - } - - var clips:Array = new Array(); - public function AddClip(clip) - { - clips.push(clip); - this.addChild(clip); - ArrangeClips(); - } - - public function ArrangeClips() - { - var numCols = Math.ceil(Math.sqrt(clips.length)); - var maxY = 0; - var maxX = 0; - var clipIndex = 0; - for (var row = 0; row < numCols; row++) - { - var clipX = 0; - var clipY = maxY; - for (var col = 0; col < numCols; col++) - { - if (clipIndex == clips.length) break; - clips[clipIndex].x = clipX; - clips[clipIndex].y = clipY; - clipX += clips[clipIndex].width; - var clipBottom = clips[clipIndex].y + clips[clipIndex].height; - if (clipBottom > maxY) maxY = clipBottom; - - var clipRight = clips[clipIndex].x + clips[clipIndex].width; - if (clipRight > maxX) maxX = clipRight; - clipIndex++; - } - } - - var scale = Math.min(startingWidth / maxX, startingHeight / maxY); - if (scale > 1) scale = 1; - - this.scaleX = this.scaleY = scale; - } - - } - -} diff --git a/old/Utils.as b/old/Utils.as deleted file mode 100755 index 02b4f12..0000000 --- a/old/Utils.as +++ /dev/null @@ -1,1202 +0,0 @@ -package old -{ - /* This class has functions similar to the Utils.as in the /flash/Dialogs folder. However, some of - * those functions are different here than in /flash/Dialogs/Utils.as for... reasons? flash folder reasons! - */ - import flash.utils.*; - import flash.net.*; - import flash.display.*; - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.geom.Point; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import flash.geom.ColorTransform; - import fl.motion.Color; - import fl.transitions.Tween; - import fl.transitions.easing.*; - import fl.transitions.TweenEvent; - import flash.net.navigateToURL; - import flash.external.ExternalInterface; - import flash.system.Capabilities; - import flash.filters.*; - import flash.filters.ColorMatrixFilter; - import com.adobe.images.JPGEncoder; - import flash.globalization.DateTimeFormatter; - - import djarts.utils.Base64; - import djarts.utils.PNGEnc; - import User.UserOptions; - - public class Utils - { - //["K","M","B","T","q", "Q", "s", "S","O","N","d","U","D","!","@","#","$","%","^","&","*"] - static var symbols = ["K","M","B","t","q", "Q", "s", "S","o","n","d","U","D","T","Qt","Qd","Sd","St","O","N","v","c"]; - static var divisors = []; - - public static function FormatBigNumber(number:*, round:Boolean=false):String - { - if (number < 0) return '-' + FormatBigNumber(Math.abs(number), round); - - var isWholeNumber = (Math.floor(number) == number); - round = round || isWholeNumber; - - if (number < 1000) - { - if (round) - { - return Math.round(number).toString(); - } - else - { - var decimalPlaces = (number >= 100) ? 1 : 2; // Below 100, show two decimal places. Above, only one. - var roundMult = Math.pow(10, decimalPlaces); - var rounded = Math.round(number); - var bigRounded = Math.round(number * roundMult); - var roundedDifferenceProportion = Math.abs(bigRounded / roundMult - rounded) / rounded; - - if (roundedDifferenceProportion < 0.001) - { - // Not a whole number, but the decimal places aren't worth showing - // Below also handles this, but is slower - return rounded.toString(); - } - else - { - var str:String = bigRounded.toString(); - str = str.substr(0, str.length - decimalPlaces) + "." + str.substr(str.length - decimalPlaces); - - while (str.charAt(str.length - 1) == "0") str = str.substr(0, str.length - 1); //should only ever happen once - if (str.charAt(str.length - 1) == ".") str = str.substr(0, str.length - 1); //probably won't happen at all - - return str; - } - } - } - - // Determine which symbol to use - var power = Math.floor(Math.log(number) / Math.log(1000)); - var index = Math.min(power-1, symbols.length-1); - var amount = number / Math.pow(1000, index+1); - var symbol = (index >= 0 && index < symbols.length) ? symbols[index] : ""; - - // If it's too big for a symbol (or if we just WANT to) - if (amount >= 1000 || UserOptions.ForceScientific) - { - // scientific notation - var power = Math.floor(Math.log(number) / Math.log(10)); - var num = number / Math.pow(10, power); - if (num == 10) { - num = 1; - power += 1; - } - var numString = "" + num; - numString = numString.substr(0, Math.min(4, numString.length)); - return numString + "e" + power; - - } - else - { - // Format with the symbol - // determine number of whole digits (will dictate how many decimals we show) - var whole = Math.floor(amount); - var amount_str:String = String(whole); - - var decimalDivider = 100/Math.pow(10,amount_str.length-1); - - //round to nearest decimal place - amount = int(amount*decimalDivider)/decimalDivider; - - var amountString:String = amount.toString(); - - var noDecimal:String = amountString.replace(".",""); - if (noDecimal.length == 2) - { - if (amountString.indexOf(".") != -1) amountString += "0"; - else amountString += ".0"; - } - else if (noDecimal.length == 1) amountString += ".00"; - - return amountString+symbol; // concat symbol - } - } - - private static var BigNumberRegex = new RegExp(/(\d*),?(\d*)(.*)/); - // Note-DG: This is mostly just used for definitions in the database, that don't require precision. - // This way we can define values in the database as 100B instead of 100000000000. - public static function ParseBigNumberString(number:String):Number - { - var regexArray:Array = BigNumberRegex.exec(number); - var magnitude = symbols.indexOf(regexArray[3]); - var thousands:Number; - if (regexArray[1]) { - thousands = regexArray[1]; - if (regexArray[2]) { // if numbers are split by comma, multiply by 1000 - thousands *= 1000; - } - } else { - thousands = 0; - } - var hundreds:Number = regexArray[2] ? regexArray[2] : 0; - - return (thousands + hundreds) * Math.pow(1000, magnitude + 1); - } - - public static function ParseNumberRange(range:String):Array - { - var split:Array = range.split(','); - return [Number(split[0]), Number(split[1])]; - } - - public static function DesaturateFilter() - { - var desatMatrix:Array = []; - var cmFilter; - - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // red - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // green - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // blue - desatMatrix = desatMatrix.concat([0, 0, 0, 1, 0]); // alpha - cmFilter = new ColorMatrixFilter(desatMatrix); - - return cmFilter; - } - - public static function GetUserAgent():String - { - try - { - var userAgent = ExternalInterface.call("window.navigator.userAgent.toString"); - var browser:String = "[Unknown Browser]"; - - if (userAgent.indexOf("Safari") != -1) - { - browser = "Safari"; - } - if (userAgent.indexOf("Firefox") != -1) - { - browser = "Firefox"; - } - if (userAgent.indexOf("Chrome") != -1) - { - browser = "Chrome"; - } - if (userAgent.indexOf("MSIE") != -1) - { - browser = "Internet Explorer"; - } - if (userAgent.indexOf("Opera") != -1) - { - browser = "Opera"; - } - } - catch (e:Error) - { - //could not access ExternalInterface in containing page - return "[No ExternalInterface]"; - } - - return browser; - } - - public static function GetScreenshot(stage:Stage):String { - var scale:Number = 0.25; - var result:String = null; - var blurFilter:BlurFilter = new BlurFilter(3, 3, BitmapFilterQuality.HIGH); - - var bData:BitmapData = new BitmapData(stage.stageWidth * scale, - stage.stageHeight * scale, false, 0x348400); - var matrix:Matrix = new Matrix(); - matrix.scale(scale, scale); - - bData.draw(stage, matrix); - bData.applyFilter(bData, bData.rect, new Point(0, 0), blurFilter); - - - var imgBytes:ByteArray = new JPGEncoder(80).encode(bData); - //var imgBytes:ByteArray = PNGEnc.encode(bData); - if (imgBytes) { - var screenshotBase64:String = Base64.encode(imgBytes); - if (screenshotBase64) { - result = screenshotBase64; - } - } - - return result; - } - - public static function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function PlayerVersion() - { - - // Get the player's version by using the getVersion() global function. - var versionNumber:String = Capabilities.version; - - // The version number is a list of items divided by "," - var versionArray:Array = versionNumber.split(","); - var length:Number = versionArray.length; - //for(var i:Number = 0; i < length; i++) _strace("versionArray["+i+"]: "+versionArray[i]); - - // The main version contains the OS type too so we split it in two - // and we'll have the OS type and the major version number separately. - var platformAndVersion:Array = versionArray[0].split(" "); - //for(var j:Number = 0; j < 2; j++) _strace("platformAndVersion["+j+"]: "+platformAndVersion[j]); - //_strace("-----"); - - var majorVersion:Number = parseInt(platformAndVersion[1]); - var minorVersion:Number = parseInt(versionArray[1]); - var buildNumber:Number = parseInt(versionArray[2]); - - return Number(majorVersion+"."+minorVersion); - } - - - public static function OpenLocalURLTop(url) - { - navigateToURL(new URLRequest(GameSettings.Approot+url), "_top" ); - } - - public static function OpenLocalURL(url) - { - navigateToURL(new URLRequest(GameSettings.Approot+url), "_blank" ); - } - - public static function OpenURL(url, window = "_blank") - { - navigateToURL(new URLRequest(url), window); - } - - public static var ExitFullScreenCallback; - - public static function WallPublish(title:String, desc1:String, desc2:String, image:String, url = null, action = null) - { - if (Utils.ExitFullScreenCallback) Utils.ExitFullScreenCallback(); - //_strace(title + "\n" + desc1 + "\n" + desc2 + "\n" + image + "\n"); - ExternalInterface.call("askToPublish", title, url, desc1, desc2, image, action); - - //if (Settings.Platform == Settings.HI5) { - //DialogManager.Instance().ShowMessageBox("The message was posted to your wall!", "", "OK", null); - //} - } - - public static function SendToRecipients(recipients:Array, description, data) - { - if (!GameSettings.IsFacebook) return; - - if (Utils.ExitFullScreenCallback) Utils.ExitFullScreenCallback(); - try { - ExternalInterface.call("sendToRecipients", recipients, description ,data); - } - catch (e) - { - _strace(e.message); - } - } - - - public static function GetFriendData() - { - try { - return ExternalInterface.call("pollInviteData"); - } - catch (e) - { - _strace(e.message); - } - } - - - public static function singleBounceEase(t:Number, b:Number, c:Number, d:Number):Number - { - t = t / d; - if (t < 0.7) { - t *= 1.0 / 0.65; - return c * (t * t) + b; - } - return c * (t * t) + b; - } - - public static function Finish(e:TweenEvent) - { - //_strace("done " + e.currentTarget.obj.x + " " + e.currentTarget.obj.y + " " + e.currentTarget.obj.scaleX + " " + e.currentTarget.obj.scaleY); - e.currentTarget.removeEventListener(TweenEvent.MOTION_FINISH, Finish); - } - public static function Popup(mc, startScale = 0.8, finishCallback = null) - { - var rect:Rectangle = mc.getRect(mc); - var targetX = mc.x; - var targetY = mc.y; - var centerX = mc.x + rect.left + mc.width / 2.0; - var centerY = mc.y + rect.top + mc.height / 2.0; - var startX = centerX - (rect.left + mc.width / 2.0) * startScale; - var startY = centerY - (rect.top + mc.height / 2.0) * startScale; - var tweenSX = new Tween(mc, "scaleX", singleBounceEase, startScale, 1.0, 4, false); - if (finishCallback) tweenSX.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenSY = new Tween(mc, "scaleY", singleBounceEase, startScale, 1.0, 4, false); - if (finishCallback) tweenSY.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenX = new Tween(mc, "x", singleBounceEase, startX, targetX, 4, false); - if (finishCallback) tweenX.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenY = new Tween(mc, "y", singleBounceEase, startY, targetY, 4, false); - if (finishCallback) tweenY.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - return [tweenSX, tweenSY, tweenX, tweenY]; - } - public static function StringSplit(s:String, delim:String, max:int = -1):Array - { - var ret:Array = s.split(delim); - if (max != -1) { - var more:String = ret.slice(max - 1).join(delim); - ret.splice(max - 1); - ret[max - 1] = more; - } - return ret; - } - - public static function StringStartsWith(str:String, substr:String):Boolean - { - if (substr.length > str.length) return false; - return (str.substr(0, substr.length) == substr); - } - - public static function StringEndsWith(str:String, substr:String):Boolean - { - if (substr.length > str.length) return false; - return (str.substr(str.length - substr.length, substr.length) == substr); - } - - public static function StringContains(str:String, substr:String):Boolean - { - return (str.indexOf(substr) !== -1); - } - - private static var vowelsAndH = { - "a":true, "A":true, - "e":true, "E":true, - "i":true, "I":true, - "o":true, "O":true, - "u":true, "U":true, - "h":true, "H":true - } - public static function StringStartsWithVowelOrH(s:String):Boolean - { - if (vowelsAndH[s.charAt(0)]) return true; - return false; - } - - public static function CopyObject(obj, except = null) - { - var i; - if (except == null) except = []; - if (obj is Array) { - var obj2 = []; - for (i = 0; i < obj.length; i++) { - obj2.push(Utils.CopyObject(obj[i])); - } - return obj2; - } - var ret:Object = {}; - for (i in obj) - { - if (except.indexOf(i) == -1) { - ret[i] = obj[i]; - } - } - - return ret; - } - public static function CopyToObject(objFrom, objTo, except = null) - { - if (except == null) except = []; - for (var i in objFrom) - { - if (except.indexOf(i) == -1) { - objTo[i] = objFrom[i]; - } - } - } - public static function CopyToObjectOnly(objFrom, objTo, only) - { - if (only == null) return; - for (var i in only) - { - if (objFrom.hasOwnProperty(only[i])) - { - objTo[only[i]] = objFrom[only[i]]; - } - } - } - - public static function ColorizeRGB(clip:MovieClip, r:int,g:int,b:int) - { - var cTransform = clip.transform.colorTransform; - cTransform.redOffset = r; - cTransform.greenOffset = g; - cTransform.blueOffset = b; - clip.transform.colorTransform = cTransform; - } - - public static function hex2rgb (hex):Object - { - var red = hex>>16; - var greenBlue = hex-(red<<16) - var green = greenBlue>>8; - var blue = greenBlue - (green << 8); - return({r:red, g:green, b:blue}); - } - - public static function RGBtoHEX(r, g, b) { - return r << 16 | g << 8 | b; - } - - /** - * NOTE: An alpha of 1 will make the object a solid color (good for silhouettes) - */ - public static function TintDisplayObject(obj:DisplayObject, color:uint = 0xffffff, alpha:Number = 1.0) - { - var cTint:Color = new Color(); - cTint.setTint(color, alpha); - obj.transform.colorTransform = cTint; - } - - // given an origin (ox, oy) and a look at point (tx, ty), - // and a clip with the given number of rotation states, which - // rotation should we pick? - public static function Rotation(ox, oy, tx, ty, rotations) - { - var delta:Point = new Point(tx - ox, ty - oy); - if (Point.distance(delta, new Point(0.0, 0.0)) < 0.00001) { - delta.y = -1.0; - } - var d = ( - (-Math.floor( - /* calculate the rotation and scale it */ - Math.atan2(delta.y, delta.x) / (Math.PI * 2.0) * rotations - + 0.5 // add 0.5 and take the floor (round to closest int) - ) - + rotations) // atan2 returns in the range -pi to pi, measured ccw from +x, - // we negate it and add rotations again to get it in the range - // [0, rotations] - % rotations) + 1; // add 1 to reference frames - return d; - } - /* performs multiple operations asynchronously, but wait for them all to finish: - * instead of calling a bunch of functions and passing callbacks, pass those callbacks to WaitForFunctions - * and use ret.callbacks[0], ret.callbacks[1], etc... as the callbacks - * this will wait until every command is complete and call all the callbacks at once. - * - * For instance, to load multiple graphics packs asynchronously and wait for them all to finish, - * call var ret = WaitForFunctions([DoneLoading, null, null, null]); to generate - * ret.callbacks[0]..ret.callbacks[3], and pass these to 4 calls to LoadExternalGraphics. - * When these 4 calls complete, the provided 4 functions will be called with the arguments returned - * from the callbacks (in this case, only DoneLoading will be called since the - * other callbacks are null). - */ - public static function WaitForFunctions(...funcs):Object - { - var ret:Object = {}; - // has a callback been hit? - ret.hit = new Array(funcs.length); - // what were the original arguments the callback was called with - ret.args = new Array(funcs.length); - // a list of the artifical callbacks we are providing - ret.callbacks = new Array(funcs.length); - // the real callbacks - ret.funcs = funcs; - ret.done = false; - - ret.immediate = []; - - for (var i = 0; i < funcs.length; i++) { - // we have to setup this temp callback in another function, because the anon function's - // activation object will contain the current scope, meaning that the variable - // i will be updated in each function; if we do it in a seperate function each - // activation object will reference a different i - ret.callbacks[i] = Utils.SetupFunction(ret, i); - } - return ret; - } - - /** - * Returns the standard money format for an integer amount - */ - public static function FormatCurrency(amount:int, symbol:String = "$"):String - { - var afterDecimal:String = (amount % 100).toString(); - while (afterDecimal.length < 2) afterDecimal = "0" + afterDecimal; //mmmm string concatenation - - var beforeDecimal:String; - if (amount > 100) - { - beforeDecimal = Math.floor(amount/100).toString(); - } - else - { - beforeDecimal = "0"; - } - - return symbol + beforeDecimal + "." + afterDecimal; - } - - public static function FormatNumber(amount){ - var whole = Math.floor(amount); - // convert the number to a string - var amount_str:String = String(whole); - var total_str:String = String(amount); - - var number_array:Array = []; - var start:Number; - var end:Number = amount_str.length; - while (end > 0) { - start = Math.max(end - 3, 0); - number_array.unshift(amount_str.slice(start, end)); - end = start; - } - - var point = total_str.indexOf("."); - - var ret = number_array.join(","); - if (point != -1 && point < total_str.length) - { - ret += total_str.substr(point); - } - - return ret; - } - - protected static function SetupFunction(ret, i):Function - { - var a:Function = - function(...rest) { - if (ret.immediate[i]) ret.immediate[i].apply(null, rest); - ret.hit[i] = true; - ret.args[i] = rest; - var ok:Boolean = true; - var j; - for (j = 0; j < ret.hit.length; j++) { - if (!ret.hit[j]) { ok = false; break; } - } - if (ok && !ret.done) { - ret.done = true; - for (j = 0; j < ret.funcs.length; j++) { - if (ret.funcs[j] != null) ret.funcs[j].apply(null, ret.args[j]); - } - } - }; - return a; - } - - // useful for the paned dialogs to show a certain pane/button - public static function OnlyVisible(obj, set:Array, index:int) - { - for (var i in set) { - if (i != index) { - obj[set[i]].visible = false; - } else { - obj[set[i]].visible = true; - } - } - } - public static function AllVisible(obj, set:Array) - { - for (var i in set) { - obj[set[i]].visible = true; - } - } - // set one of a list of tabs to be enabled - public static function OnlyToggled(obj, set:Array, index:int) - { - for (var i in set) { - if (i != index) { - obj[set[i]].SetToggled(false); - } else { - obj[set[i]].SetToggled(true); - } - } - } - // get the frame number of a label in the timeline - public static function GetLabelFrame(mc, name:String):int - { - for (var l in mc.currentLabels) { - if (mc.currentLabels[l].name == name) return mc.currentLabels[l].frame; - } - return 1; - } - // generate a quick text field of a certain color/style - public static function BasicTextField(color:uint, - size:int, - font:String, - text:String, - additional:Object = null, - align = "left"):TextField - { - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.align = align; - if (additional != null) for (var a in additional) f[a] = additional[a]; - f.font = font; - f.color = color; - f.size = size; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.text = text; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - return t; - } - public static function var_dump(_obj, name = "Dump") - { - _strace(name + " " + (_obj) + " {"); - flash.utils.describeType(_obj); - var varList:XMLList = flash.utils.describeType(_obj)..variable; - - for(var i:int; i < varList.length(); i++) - { - //Show the name and the value - _strace(" " + varList[i].@name+' = '+ _obj[varList[i].@name]); - } - _strace("}"); - } - - public static function SetChildFrames(parentClip, frame, exclude = null) - { - if (parentClip is MovieClip && parentClip.name != exclude) - { - parentClip.gotoAndStop(frame); - for (var i = 0; i < parentClip.numChildren; i++) - { - Utils.SetChildFrames(parentClip.getChildAt(i), frame, exclude); - } - } - } - - public static function SetChildFramesNoParent(parentClip, frame, exclude = null) - { - if (parentClip is MovieClip && parentClip.name != exclude) - { - for (var i = 0; i < parentClip.numChildren; i++) - { - Utils.SetChildFrames(parentClip.getChildAt(i), frame, exclude); - } - } - } - - //modifies the array passed as parameter, following the MO of the built in Array.sort() - public static function insertionSort(array:Array, compareFunction:Function):void - { - for(var i:int=1; i < array.length; i++) - { - var value:Object = array[i]; - var k:int=i-1; - while( k >= 0 && compareFunction(array[k], value) == -1) - { - array[k+1]=array[k]; - k--; - } - array[k+1]=value; - } - } - - - public static function Screenshot(sourceClip, receiverURL, filename) - { - - var jpgSource:BitmapData; - - if (sourceClip is Stage) - { - jpgSource = new BitmapData (sourceClip.stageWidth, sourceClip.stageHeight); - } else { - jpgSource = new BitmapData (sourceClip.width, sourceClip.height); - } - - jpgSource.draw(sourceClip); - - var jpgEncoder:JPGEncoder = new JPGEncoder(85); - var jpgStream:ByteArray = jpgEncoder.encode(jpgSource); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - var jpgURLRequest:URLRequest = new URLRequest(receiverURL+"?name="+filename); - jpgURLRequest.requestHeaders.push(header); - jpgURLRequest.method = URLRequestMethod.POST; - jpgURLRequest.data = jpgStream; - navigateToURL(jpgURLRequest, "_blank"); - - } - - - public static function SetColors(clip, color) - { - var colorTransform:ColorTransform; - - if (clip == null || color == null) return; - - if (clip.hasOwnProperty("outline") && clip.outline != null) - { - colorTransform = clip.outline.transform.colorTransform; - colorTransform.color = color.Outline; - clip.outline.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryOutline") && clip.secondaryOutline != null) - { - colorTransform = clip.secondaryOutline.transform.colorTransform; - colorTransform.color = color.LightOutline; - clip.secondaryOutline.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("color") && clip.color != null) - { - colorTransform = clip.color.transform.colorTransform; - colorTransform.color = color.Primary; - clip.color.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryColor") && clip.secondaryColor != null) - { - colorTransform = clip.secondaryColor.transform.colorTransform; - colorTransform.color = color.Secondary; - clip.secondaryColor.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("shadow") && clip.shadow != null) - { - colorTransform = clip.shadow.transform.colorTransform; - colorTransform.color = color.Shadow; - clip.shadow.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryShadow") && clip.secondaryShadow != null) - { - colorTransform = clip.secondaryShadow.transform.colorTransform; - colorTransform.color = color.SecondaryShadow; - clip.secondaryShadow.transform.colorTransform = colorTransform; - } - } - /* returns a rect with the x, and y pos to center and the scaleX and scaleY as width and height */ - public static function GetUniformScaleRect(clip:MovieClip, maxWidth, maxHeight) - { - var rect:Rectangle = new Rectangle(0,0,0,0); - - var widthScale = Math.min(maxWidth / clip.width, 999); - var heightScale = Math.min(maxHeight / clip.height, 999); - - var scale = 1; - if (widthScale > heightScale) - { - scale = heightScale; - } else { - scale = widthScale; - } - - rect.width = clip.width * scale; - rect.height = clip.height * scale; - - var pb = clip.getBounds(clip); - var xadjust = -pb.left * scale; - var yadjust = -pb.top * scale; - - rect.x = xadjust + (maxWidth - rect.width) / 2; - rect.y = yadjust + (maxHeight - rect.height) / 2; - - rect.width = scale; - rect.height = scale; - - return rect; - } - - public static function Dec2Hex(d) - { - var chars:String = "0123456789ABCDEF"; - var str:String = ""; - while (d > 0 || str.length < 2) - { - var digit = d % 16; - d = (d - digit) / 16; - str = chars.charAt(digit) + str; - } - return str; - } - - public static function Hex2Dec(h:String) - { - var chars:String = "0123456789ABCDEF"; - var val = 1; - var res = 0; - for (var i = h.length - 1; i >= 0; i--) - { - res += chars.indexOf(h.substr(i, 1)) * val; - val *= 16; - } - return res; - } - - public static function ShallowCopyArray(array:Array) - { - if (!array) return null; - - var newArray:Array = []; - for (var i:int = 0; i < array.length; i++) - { - newArray.push(array[i]); - } - return newArray; - } - - /* Note: Will fail if any items in either array have reference type semantics (unless they point to the same object) - * (as opposed to value type semantics) - */ - public static function areEqual(a:Array,b:Array):Boolean { - if(a.length != b.length) { - return false; - } - var len:int = a.length; - for(var i:int = 0; i < len; i++) { - if(a[i] !== b[i]) { - return false; - } - } - return true; - } - - /* Note: Will fail if any items in either array have reference type semantics - * (as opposed to value type semantics) - */ - public static function objectsAreEqual(a:Object,b:Object):Boolean { - - for (var i in a) - { - if (!b.hasOwnProperty(i) || a[i] != b[i]) return false; - } - - return true; - } - - public static function DeepCopyClone (source : Object) : * - { - var array : ByteArray = new ByteArray (); - - array.writeObject (source); - array.position = 0; - - return array.readObject (); - } - - // {a:1, b:2} => [1,2] - public static function ObjectValues (obj:Object):Array { - var array = []; - for (var key in obj) array.push(obj[key]); - return array; - } - - // {a:1, b:2} => ["a","b"] - public static function ObjectKeys (obj:Object):Array { - var array = []; - for (var key in obj) array.push(key); - return array; - } - - // normal random variate generator; mean m, standard deviation s - public static function BoxMullerRandomNormal(m:Number, s:Number) : Number - { - var x1, x2, w, y1:Number; - var y2:Number; - var use_last:Boolean = false; - - if (use_last == true) /* use value from previous call */ - { - y1 = y2; - use_last = false; - } - else - { - do { - x1 = 2.0 * Math.random() - 1.0; - x2 = 2.0 * Math.random() - 1.0; - w = x1 * x1 + x2 * x2; - } while ( w >= 1.0 ); - - w = Math.sqrt( (-2.0 * Math.log( w ) ) / w ); - y1 = x1 * w; - y2 = x2 * w; - use_last = true; - } - - return( m + y1 * s ); - } - - public static function SanitizeNumber(n) - { - if (n is Number) - { - if (n == Number.NEGATIVE_INFINITY || n == Number.POSITIVE_INFINITY || n == Number.NaN) return 0; - } - return n; - } - - public static function IsNumberInvalid(n) - { - if (n is Number) - { - if (n == Number.NEGATIVE_INFINITY || n == Number.POSITIVE_INFINITY || n == Number.NaN) return true; - } - return false; - } - - public static function LimitNumberToMax(n) - { - if (n == Number.POSITIVE_INFINITY) return Number.MAX_VALUE; - return n; - } - - /* - value= Math.round(20/7); - value= int((20/7)*10)/10; - value= int((20/7)*100)/100; - value= int((20/7)*1000)/1000; - value= int((20/7)*10000)/10000; - */ - public static function RoundToDecimalPlaces(number:Number, places:int) - { - return Math.round((number)*Math.pow(10,places))/Math.pow(10,places); - } - - public static function GetShuffledArray(a:Array) : Array - { - var r:Array = a.concat(); - r.sort(randomSort); - return r; - } - - ///Convenience function since I keep forgetting the name of randomSort (hint: it's randomSort) - public static function ShuffleArray(a:Array) - { - a.sort(randomSort); - } - - public static function PickRandom(a:Array) - { - return a[Math.floor(Math.random() * a.length)]; - } - - /** - * Returns n elements of array a, up to a maximum of a's length. - * If forceCopy is set, the returned array will always be a new instance. - */ - public static function PickRandomSet(a:Array, n:int, forceCopy:Boolean=false):Array - { - if (a.length <= n || a.length == 0) - { - if (forceCopy) return a.concat(); - else return a; - } - if (n == 1) return [PickRandom(a)]; - - var shuffled:Array = GetShuffledArray(a); - return shuffled.slice(0, n); - } - - /** - * Does not randomly sort an array! To do that, Use the default array.sort with this as its argument. - * If you want a new, shuffled array, use GetShuffledArray - */ - public static function randomSort(a:*, b:*) : Number - { - if (Math.random() < 0.5) return -1; - else return 1; - } - - /** - * Returns the union of arr1 and arr2. If the elements are not primitive types, you'll need to provide a sorting function. - * If inPlace, a1 and a2 will be sorted. - * If they already contain duplicates, then all bets are off. - */ - public static function MergeArrays(arr1:Array, arr2:Array, sortFunc:Function = null, inPlace:Boolean = false) : Array - { - var ret:Array = []; - var a1:Array = (inPlace) ? arr1 : arr1.slice(); - var a2:Array = (inPlace) ? arr2 : arr2.slice(); - - var len1:uint = a1.length; - var len2:uint = a2.length; - var i1:uint = 0; - var i2:uint = 0; - - //Boring cases - if (len1 == 0 && len2 == 0) return ret; - if (len1 == 0) return (inPlace) ? a2.slice() : a2; - if (len2 == 0) return (inPlace) ? a1.slice() : a1; - - if (sortFunc) - { - a1.sort(sortFunc); - a2.sort(sortFunc); - } - else - { - a1.sort(); - a2.sort(); - } - - while (i1 < len1) - { - //add all from a2 up to a1[i1] - while (i2 < len2 && a2[i2] <= a1[i1]) - { - ret.push(a2[i2]); - i2 += 1; - } - if (ret.length == 0 || a1[i1] != ret[ret.length-1]) ret.push(a1[i1]); - i1 += 1; - } - - while (i2 < len2) ret.push(a2[i2]); - - return ret; - } - - public static function ConvertToHHMMSS(seconds:Number):String - { - var s:Number = seconds % 60; - var m:Number = Math.floor((seconds % 3600 ) / 60); - var h:Number = Math.floor(seconds / (60 * 60)); - - var hourStr:String = (h == 0) ? "" : DoubleDigitFormat(h) + ":"; - var minuteStr:String = DoubleDigitFormat(m) + ":"; - var secondsStr:String = DoubleDigitFormat(s); - - return hourStr + minuteStr + secondsStr; - } - - public static function DoubleDigitFormat(num:uint):String - { - if (num < 10) - { - return ("0" + num); - } - return String(num); - } - - public static function CapitolizeString(str:String) : String - { - var firstChar:String = str.substr(0, 1); - var restOfString:String = str.substr(1, str.length); - - return firstChar.toUpperCase()+restOfString.toLowerCase(); - } - - // ^ Nice spelling, goof! - public static function CapitalizeString(str:String) : String - { - return CapitolizeString(str); - } - - public static function GetListString(listStrings:Array) : String - { - var andString:String = "&"; - var count:int = 0; - - var listString:String = ""; - for (var i = 0; i < listStrings.length; i++) - { - if (count > 0 && listStrings.length == 2) listString += " "+andString+" "; // For just 2 items - else if (count == listStrings.length-1 && listStrings.length > 2) - { - // For adding "and" at the end of 3+ items. It is: ", and $(item)" - var endingString:String = ""; - endingString = endingString.replace("$(item)", listStrings[i]); - listString += endingString; - count++; - continue; - } - else if (count > 0) listString += ", "; // Comma separated list - - listString += listStrings[i]; - count++; - } - - return listString; - } - - /* - * Flash doesn't like the way MySQL prints dates (2016-06-02 13:00:00) - * "The year month and day terms can be separated by a forward slash (/) or by spaces, but never by a dash (-)." - */ - public static function ParseDate (dateString:String) : Date - { - var pattern:RegExp = /-/g; - var date = new Date(); - dateString = dateString.replace(pattern, "/"); - date.setTime(Date.parse(dateString)); - return date; - } - - /* - * For display only, not intended to be read by ParseDate - * Tuesday, June 7th, 2016 at 10:32 AM - */ - public static function FormatDate (date:Date) : String - { - var f:DateTimeFormatter = new DateTimeFormatter("en-US"); - var dateStr:String; - var lastChar:String; - - //Flash can't do "1st", "2nd", etc - - f.setDateTimePattern("d"); - dateStr = f.format(date); - lastChar = dateStr.charAt(dateStr.length - 1); - - if (lastChar == "1" && dateStr != "11") dateStr += "st"; - else if (lastChar == "2" && dateStr != "12") dateStr += "nd"; - else if (lastChar == "3" && dateStr != "13") dateStr += "rd"; - else dateStr += "th"; - - f.setDateTimePattern("EEEE, MMMM '" + dateStr + "', yyyy 'at' h:mm a"); - return f.format(date); - } - - /* Simply counts the number of properties on the object - */ - public static function CountObjectParameters(obj:Object):int - { - var cnt:int=0; - - for (var s:String in obj) cnt++; - - return cnt; - } - - /** - * For when shit gets real - */ - public static function PrintStackTrace() - { - try { - throw new Error('StackTrace'); - } catch (e:Error) { - _strace(e.getStackTrace()); - } - } - } -} \ No newline at end of file diff --git a/org/aszip/compression/CompressionMethod.as b/org/aszip/compression/CompressionMethod.as deleted file mode 100644 index 42fe7a0..0000000 --- a/org/aszip/compression/CompressionMethod.as +++ /dev/null @@ -1,17 +0,0 @@ -package org.aszip.compression - -{ - - /** - * The CompressionMethod class lets you choose the compression algorithms used for the files in the ZIP. - */ - public class CompressionMethod - - { - - public static var GZIP:String = 'GZIP'; - public static var NONE:String = 'NONE'; - - } - -} \ No newline at end of file diff --git a/org/aszip/crc/CRC32.as b/org/aszip/crc/CRC32.as deleted file mode 100644 index fcbc4f0..0000000 --- a/org/aszip/crc/CRC32.as +++ /dev/null @@ -1,63 +0,0 @@ -/** -* AS3 CRC32 algorithm implementation -*/ - -package org.aszip.crc -{ - - import flash.utils.ByteArray; - - public class CRC32 { - - private var crc32:int; - private static var CRCTable:Array = initLookupTable(); - - private static function initLookupTable ():Array - { - - var polynomial:int = 0xEDB88320; - var CRC32Table:Array = new Array(256); - - var i:int = 256; - var j:int = 8; - - while ( i-- ) - - { - - var crc:int = i; - - while ( j-- ) crc = (crc & 1) ? (crc >>> 1) ^ polynomial : (crc >>> 1); - - j = 8; - - CRC32Table [ i ] = crc; - - } - - return CRC32Table; - - } - - public function generateCRC32 ( pBytes:ByteArray ):void - { - - var length:int = pBytes.length; - - var crc:int = ~crc32; - - for ( var i:int = 0; i < length; i++ ) crc = ( crc >>> 8 ) ^ CRCTable[ pBytes[i] ^ (crc & 0xFF) ]; - - crc32 = ~crc; - - } - - public function getCRC32 ():int - { - - return crc32 & 0xFFFFFFFF; - - } - - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/flash/util/RectangleNode.as b/flash/util/RectangleNode.as new file mode 100644 index 0000000..6f31e44 --- /dev/null +++ b/flash/util/RectangleNode.as @@ -0,0 +1,178 @@ +package util { + import flash.geom.Rectangle; + + public class RectangleNode + { + public var Left:RectangleNode = null; + public var Right:RectangleNode = null; + public var Rect:Rectangle = null; + public var InUse:Boolean = false; + public var Removed:Boolean = false; + public var Parent:RectangleNode = null; + public var AllocationID = 0; + public var Host:RectanglePacker= null; + public var MinAllocationID = 0; + public var NodeID; + public static var NextNodeID = 0; + + public var DontRemove = false; + + public var LastAccessTime = 0; + + public var Flags = []; + + public var UpdateTo:RectangleNode = null; + + /* + public function get Removed() + { + return _Removed; + } + + public function set Removed(r) + { + this._Removed = r; + } + + public function get Host():RectanglePacker + { + return _Host; + } + public function set Host(p:RectanglePacker) + { + this._Host = p; + + if (_Left && _Left.Host != p) + { + throw new Error("bad left host"); + } + if (_Right && _Right.Host != p) + { + throw new Error("bad right host"); + } + if (_Parent && _Parent.Host != p) + { + throw new Error("bad parent host"); + } + + } + + public function get Left():RectangleNode + { + return _Left; + } + public function set Left(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad left host"); + } + _Left = n; + } + public function get Right():RectangleNode + { + return _Right; + } + public function set Right(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad right host"); + } + _Right = n; + } + + public function get Parent():RectangleNode + { + return _Parent; + } + public function set Parent(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad parent host"); + } + _Parent = n; + } + */ + public function get IsFreeSpace() + { + return Left == null && Right == null && !InUse; + } + public function UpdateLinksFromNode(node:RectangleNode) + { + if (node.Parent) + { + if (node.Parent.Left == node) + { + node.Parent.Left = this; + } + if (node.Parent.Right == node) + { + node.Parent.Right = this; + } + } + if (node.Left) + { + node.Left.Parent = this; + } + if (node.Right) + { + node.Right.Parent = this; + } + } + public function MakeFromNode(node:RectangleNode) + { + //_Host = node.Host; + Host = node.Host; + Left = node.Left; + Right = node.Right; + Parent = node.Parent; + AllocationID = node.AllocationID; + InUse = node.InUse; + MinAllocationID = node.MinAllocationID; + NodeID = node.NodeID; + Rect = node.Rect.clone(); + Removed = node.Removed; + DontRemove = node.DontRemove; + } + public function RectangleNode(x, y, w, h, host:RectanglePacker) + { + this.NodeID = NextNodeID++; + this.Host = host; + this.Rect = new Rectangle(x, y, w, h); + } + public function OutputJSON() + { + var node = {}; + node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; + node.in_use = InUse; + node.id = NodeID; + if (this.Left) node.left = this.Left.OutputJSON(); + if (this.Right) node.right = this.Right.OutputJSON(); + return node; + } + + public function ReadJSON(details) + { + details.new_node = this; + this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); + this.Removed = false; + + this.InUse = details.in_use; + + if (details.hasOwnProperty("right")) + { + this.Right = new RectangleNode(0, 0, 0, 0, this.Host); + Right.ReadJSON(details.right); + Right.Parent = this; + } + if (details.hasOwnProperty("left")) + { + this.Left = new RectangleNode(0, 0, 0, 0, this.Host); + Left.ReadJSON(details.left); + Left.Parent = this; + } + } + } +} diff --git a/flash/util/RectanglePacker.as b/flash/util/RectanglePacker.as new file mode 100644 index 0000000..597d7fd --- /dev/null +++ b/flash/util/RectanglePacker.as @@ -0,0 +1,562 @@ +package util { + import flash.geom.*; + import flash.display.BitmapData; + import flash.display.MovieClip; + import flash.text.TextField; + import flash.events.*; + import flash.sampler.StackFrame; + + public class RectanglePacker + { + protected var w:int; + protected var h:int; + protected var root:RectangleNode; + public var NextAllocationID = 0; + + public function get width():int { return w; } + public function get height():int { return h; } + + public function RectanglePacker(w, h) + { + this.w = w; + this.h = h; + root = new RectangleNode(0, 0, w, h, this); + root.AllocationID = -1; + } + protected var area = 0; + + protected var testRender:MovieClip = new MovieClip(); + + public function GetRoot():RectangleNode + { + return root; + } + + public function GetLeafNodes():Array + { + return GetLeafNodesInternal(root); + } + + protected function GetLeafNodesInternal(n:RectangleNode):Array + { + if (n.InUse) return [n]; + var ret:Array = new Array(); + if (n.Left) ret = GetLeafNodesInternal(n.Left); + if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); + return ret; + } + + public function GetUsedArea() + { + return area; + } + + public function get efficiency() + { + return area / (w * h); + } + + protected function RectCost(w, h) + { + if (w == 0 || h == 0) return 99999999; + return (Math.max(w, h) / Math.min(w, h)) * w * h; + } + + protected function EnumerateTree(r:RectangleNode = null, indent = "") + { + if (r == null) r = this.root; + var str = ""; + str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; + if (r.Left) str += EnumerateTree(r.Left, indent + " "); + if (r.Right) str += EnumerateTree(r.Left, indent + " "); + return str; + } + + /* + * Remove a list of nodes from the tree. + * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree + * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, + leaving the original objects intact (in case something still references them) + */ + public function RemoveNodes(nodes:Array, fullyDestroy = true) + { + + /* DEBUG CHECKS */ + /* + this.PerformDebugCheck(); + + var str = ""; + for (var i = 0; i < nodes.length; i++) + { + str += nodes[i].NodeID + "\n"; + } + + var orig = nodes.concat(); + + var strs = [str, EnumerateTree()]; + + RenderDetailsBox.StartTrack("PackRemoveTime"); + + for (var i = 0; i < nodes.length; i++) + { + var n:RectangleNode = nodes[i]; + if (n.Host != this) + { + throw new Error("bad host!"); + } + } + */ + /* END DEBUG CHECKS */ + + var i, n:RectangleNode, p:RectangleNode; + + // setup the Removed flag on every node that should be removed + // we also check at this time to see if any more nodes need to be removed, such as a parent of + // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + if (n.Host == this) + { + n.Removed = true; + + if (n.InUse) + { + // sum up the total removed area + area -= n.Rect.width * n.Rect.height; + } + + if (n.Parent != null) + { + p = n.Parent; + // check and see if the current node's parent still has any valid children + if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) + { + // all of the current nodes siblings are either being removed or are blank, so + // we can remove the parent too + if (p.Left.IsFreeSpace) + { + // the left child was empty space before, so we can remove it (if it wasn't + // empty space it is already being removed so it doesn't need to be added + // to the list) + if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); + } + if (p.Right.IsFreeSpace) + { + // the right child was empty space before, so we can remove it + if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); + } + if (p != root && nodes.indexOf(p) == -1) + { + // remove the parent node too (provided it isn't the root!) + nodes.push(p); + } + } + } + } + } + + // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, + // so go ahead and remove them + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + + if (n.Parent != null) + { + // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not + // also getting removed!) + p = n.Parent; + + if (!p.Removed) + { + if (p.Left && p.Right) + { + var newNode:RectangleNode; + if (p.Left.Removed && p.Right.Removed) + { + // both children were removed, but the parent wasn't, so the parent must be root + // (since we never remove the root) + if (p != root) + { + throw new Error("should be root"); + } + p.Left.Parent = null; + p.Right.Parent = null; + p.Left = null; + p.Right = null; + p.InUse = false; + } else if (!p.Left.Removed) { + // Right node removed, Left node not removed + if (!p.Left.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Right); + newNode.UpdateLinksFromNode(p.Right); + } + // Left node is used + p.Right.InUse = false; + p.Right.Left = null; + p.Right.Right = null; + p.Right.Removed = false; + } else { + throw new Error("should have been caught above!"); + } + } else { + // Left node removed, Right node not removed + if (!p.Right.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Left); + newNode.UpdateLinksFromNode(p.Left); + } + // Left node is used + //p.Left.Removed = true; + p.Left.InUse = false; + p.Left.Left = null; + p.Left.Right = null; + p.Left.Removed = false; + //p.Left.Parent = null; + } else { + throw new Error("should have been caught above!"); + } + } + } else { + // huh? how does n.Parent == p but p has no children? something went wrong + throw new Error("shouldn't have gotten here"); + } + } + } + //strs.push(EnumerateTree()); + } + } + + public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode + { + + var node:RectangleNode = FindSizedNode(w, h, root); + + if (node == null) + { + //UHOH, texture full + return null; + } + area += w * h; + node.InUse = true; + + var splitVertFirstCost = 0; + if (w < node.Rect.width) + { + splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); + } + + var splitHorizFirstCost = 0; + if (h < node.Rect.height) + { + splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); + } + + + + if (splitVertFirstCost <= splitHorizFirstCost) + { + node.Flags.push("SplitVertFirst"); + if (w < node.Rect.width) + { + node.Flags.push("SplitVert"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + if (h < node.Rect.height) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + } else { + node.Flags.push("SplitHorzFirst"); + if (h < node.Rect.height) + { + node.Flags.push("SplitVert"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + if (w < node.Rect.width) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + } + NextAllocationID++; + if (useInstead) + { + useInstead.MakeFromNode(node); + useInstead.UpdateLinksFromNode(node); + useInstead.Flags = node.Flags; + node = useInstead; + node.Flags.push("UseInstead"); + } + + //if (!CheckOKNode(node)) node.Flags.push("BadNode"); + + return node; + } + public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) + { + if (r == null) r = this.root; + if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) + { + var ancestor:RectangleNode = FindCommonNode(n, r); + throw new Error("bad node allocated!"); + return false; + } + var ok = true; + if (r.Left) ok = ok && CheckOKNode(n, r.Left); + if (r.Right) ok = ok && CheckOKNode(n, r.Right); + return ok; + } + + public function PerformDebugCheck() + { + DebugInternal(this.root); + } + + protected function DebugInternal(n:RectangleNode) + { + if (n.Host != this) + { + throw new Error("problem with host!"); + } + if (n.IsFreeSpace) + { + if (n.Left || n.Right) + { + throw new Error("shouldn't have children"); + } + } + if ((n.Left && !n.Right) || (n.Right && !n.Left)) + { + throw new Error("mismatched children"); + } + if (n.Left && n.Left.Parent != n) + { + throw new Error("left child has bad parent"); + } + if (n.Right && n.Right.Parent != n) + { + throw new Error("right child has bad parent"); + } + if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) + { + throw new Error("problem with parent"); + } + if (n.Left) DebugInternal(n.Left); + if (n.Right) DebugInternal(n.Right); + } + + public function FindCommonNode(a:RectangleNode, b:RectangleNode) + { + var aHistory = []; + var bHistory = []; + while (a != null) + { + aHistory.push(a); + a = a.Parent; + } + while (b != null) + { + bHistory.push(b); + b = b.Parent; + } + var i = aHistory.length - 1; + var j = bHistory.length - 1; + var same = null; + while (i >= 0 && j >= 0) + { + if (aHistory[i] == bHistory[j]) + { + same = aHistory[i]; + } else { + break; + } + i--; + j--; + } + return same; + } + + public function TestRender() + { + while (testRender.numChildren > 0) + { + testRender.removeChildAt(0); + } + testRender.graphics.clear(); + TestRenderNode(root, testRender); + return testRender; + } + protected function TestRenderNode(n:RectangleNode, m:MovieClip) + { + var g:MovieClip = new MovieClip(); + m.addChild(g); + g.graphics.lineStyle(1, 0, 1); + if (n.Left != null) TestRenderNode(n.Left, m); + if (n.Left != null) TestRenderNode(n.Right, m); + if (n.InUse) + { + g.graphics.beginFill(0xFFFF00, 0.2); + } + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + if (n.InUse) + { + g.graphics.endFill(); + var t:TextField = new TextField(); + t.text = n.NodeID; + t.x = n.Rect.x + n.Rect.width / 2.0; + t.y = n.Rect.y + n.Rect.height / 2.0; + g.addChild(t); + g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); + g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); + } + + } + public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) + { + if (n.InUse) + { + //_trace(Math.round(n.LastAccessTime / 1000)); + } + var p:RectangleNode = n.Parent; + if (p) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); + g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); + g.graphics.endFill(); + t.text = p.NodeID; + if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); + g.oldListener = function(e){MouseOver(p, g, t);}; + g.addEventListener(MouseEvent.CLICK, g.oldListener); + } + } + public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(0xFFFF00, 0.2); + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + g.graphics.endFill(); + t.text = n.NodeID; + } + protected function SplitVert(node:RectangleNode, leftWidth) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function SplitHoriz(node:RectangleNode, topHeight) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode + { + if (node.InUse) return null; + if (node.Rect.width >= w && node.Rect.height >= h) + { + if (node.Left != null && node.Right != null) + { + var t:RectangleNode = FindSizedNode(w, h, node.Left); + if (t != null) return t; + t = FindSizedNode(w, h, node.Right); + return t; + } else { + return node; + } + } + return null; + } + + public function LoadTree(details) + { + this.root = new RectangleNode(0, 0, 0, 0, this); + root.ReadJSON(details); + + this.NextAllocationID = 0; + this.area = 0; + + var queue:Array = new Array(); + queue.push(root); + while (queue.length > 0) + { + var node:RectangleNode = queue.shift(); + node.AllocationID = NextAllocationID; + node.MinAllocationID = NextAllocationID; + if (node.Left) queue.push(node.Left); + if (node.Right) queue.push(node.Right); + if (node.InUse) this.area += node.Rect.width * node.Rect.height; + } + NextAllocationID++; + } + + public function GetNodePath(node:RectangleNode) + { + var output:String = ""; + while (node != this.root) + { + output = (node == node.Parent.Left ? "l" : "r") + output; + node = node.Parent; + } + return output; + } + + public function GetNodeFromPath(path:String):RectangleNode + { + var node:RectangleNode = this.root; + for (var i = 0; i < path.length; i++) + { + if (!node) return null; + if (path.charAt(i) == "r") + { + node = node.Right; + } else { + node = node.Left; + } + } + return node; + } + } +} diff --git a/flash/util/Utils.as b/flash/util/Utils.as new file mode 100644 index 0000000..f792003 --- /dev/null +++ b/flash/util/Utils.as @@ -0,0 +1,389 @@ +package util +{ + import flash.display.*; + import flash.geom.*; + public class Utils + { + public static function GetChildren(clip:MovieClip):Array + { + var ret:Array = []; + for (var i = 0; i < clip.numChildren; i++) + { + ret.push(clip.getChildAt(i)); + } + return ret; + } + + /* + * angle difference + * (range -Math.PI to Math.PI) + */ + public static function GetAngleDiff(a, b) + { + var angleDiff = b - a; + + while (angleDiff > Math.PI) + { + angleDiff -= Math.PI * 2; + } + while (angleDiff < -Math.PI) + { + angleDiff += Math.PI * 2; + } + return angleDiff; + } + + /* + * angle difference + * (range 0 to Math.PI) + */ + public static function GetAngleDiffAbs(a, b) + { + var angleDiff = GetAngleDiff(a, b); + while (angleDiff < 0) + { + angleDiff += Math.PI * 2; + } + + if (angleDiff > Math.PI) + { + angleDiff = Math.PI * 2 - angleDiff; + } + + return angleDiff; + } + + public static function GetTransform(from:Matrix, to:Matrix) + { + var i:Matrix = from.clone(); + i.invert(); + var m:Matrix = to.clone(); + m.concat(i); + return m; + } + + public static function Decompose(m:Matrix) + { + var s:Point = ScaleFromMat(m); + m = m.clone(); + + var sxUnit = s.x >= 0 ? 1 : -1; + var syUnit = s.y >= 0 ? 1 : -1; + + m.scale(sxUnit, syUnit); + + //m.a /= sxUnit; + //m.d /= syUnit; + var rot = RotFromMat(m); + return {sx:s.x, sy:s.y, rot:rot}; + } + + public static function RotFromMat(m:Matrix) + { + return Math.atan2(-m.c, m.a); + } + + public static function ScaleFromMat(m:Matrix):Point + { + var xAxisX = m.a; + var xAxisY = m.c; + + var yAxisX = m.b; + var yAxisY = m.d; + + var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); + if (m.a < 0) sx *= -1; + + var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); + if (m.d < 0) sy *= -1; + + return new Point(sx, sy); + } + + public static function TransformRect(r:Rectangle, m:Matrix) + { + var p1:Point = new Point(r.left, r.top); + var p2:Point = new Point(r.right, r.top); + var p3:Point = new Point(r.left, r.bottom); + var p4:Point = new Point(r.right, r.bottom); + + p1 = m.transformPoint(p1); + p2 = m.transformPoint(p2); + p3 = m.transformPoint(p3); + p4 = m.transformPoint(p4); + + r.left = Math.min(p1.x, p2.x, p3.x, p4.x); + r.top = Math.min(p1.y, p2.y, p3.y, p4.y); + r.right = Math.max(p1.x, p2.x, p3.x, p4.x); + r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); + } + + public static function RoundRect(r:Rectangle) + { + r.left = Math.floor(r.left); + r.top = Math.floor(r.top); + r.right = Math.ceil(r.right); + r.bottom = Math.ceil(r.bottom); + } + + public static function ScaleRect(r:Rectangle, s) + { + r.left *= s; + r.top *= s; + r.right *= s; + r.bottom *= s; + } + + public static function RecursivelyStop(clip) + { + if (clip is MovieClip) + { + clip.stop(); + } + if (clip is DisplayObjectContainer) + { + for (var i = 0; i < clip.numChildren; i++) + { + RecursivelyStop(clip.getChildAt(i)); + } + } + } + + public static function WeirdGotoFrame(clip:MovieClip, frame) + { + var dir = clip.currentFrame > frame ? -1 : 1; + while (clip.currentFrame != frame) + { + RecurseDir(clip, dir); + } + } + + protected static function RecurseDir(clip:MovieClip, dir) + { + for (var i = 0; i < clip.numChildren; i++) + { + var child = clip.getChildAt(i); + if (child is MovieClip) + { + RecurseDir(child, dir); + } + } + if (dir == 1) + { + clip.nextFrame(); + } else { + clip.prevFrame(); + } + } + + protected static var tempSpace:BitmapData = null; + protected static var tempSpaceRect:Rectangle = new Rectangle(); + protected static var tempSpaceMatrix:Matrix = new Matrix(); + protected static var tempSpaceZero:Point = new Point(); + protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); + protected static var lastDrawOffset:Point = new Point(); + public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle + { + if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); + + var oldPad = 0; + var padAmount = 5; + + var ret:Rectangle = new Rectangle(); + + var baseBounds:Rectangle = clip.getBounds(clip); + + var boundsClip:DisplayObject = null; + if (clip is DisplayObjectContainer) + { + boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); + } + + if (boundsClip != null) + { + baseBounds = boundsClip.getBounds(clip); + } + + if (useMatrix) + { + TransformAABBRect(baseBounds, useMatrix); + } + + if (boundsClip != null) + { + return baseBounds; + } + + var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); + var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); + if (tempSpace == null) + { + tempSpace = new BitmapData(minW, minH, true, 0x0); + } + if (tempSpace.width < minW || tempSpace.height < minH) + { + tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); + } + + var r:Rectangle = new Rectangle(); + + baseBounds.left = Math.floor(baseBounds.left); + baseBounds.right = Math.ceil(baseBounds.right); + + baseBounds.top = Math.floor(baseBounds.top); + baseBounds.bottom = Math.ceil(baseBounds.bottom); + + var i; + + var needsChecking = true; + while (needsChecking) + { + needsChecking = false; + r.left = baseBounds.left - padAmount; + r.right = baseBounds.right + padAmount; + + r.top = baseBounds.top - padAmount; + r.bottom = baseBounds.bottom + padAmount; + + ret = r.clone(); + + tempSpaceRect.x = tempSpaceRect.y = 0; + tempSpaceRect.width = tempSpace.width; + tempSpaceRect.height = tempSpace.height; + tempSpace.fillRect(tempSpaceRect, 0x0); + + tempSpaceMatrix.identity(); + if (useMatrix) + { + tempSpaceMatrix.a = useMatrix.a; + tempSpaceMatrix.b = useMatrix.b; + tempSpaceMatrix.c = useMatrix.c; + tempSpaceMatrix.d = useMatrix.d; + tempSpaceMatrix.tx = useMatrix.tx; + tempSpaceMatrix.ty = useMatrix.ty; + } + tempSpaceMatrix.translate(-r.left, -r.top); + + lastDrawOffset.x = -r.left; + lastDrawOffset.y = -r.top; + tempSpace.draw(clip, tempSpaceMatrix); + + tempSpaceRect.width = 1; + tempSpaceRect.height = r.height; + + var sideMovedIn = 0; + for (i = 0; i < r.width; i++) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.left++; + sideMovedIn++; + } + } + if (ret.left < baseBounds.left - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.width - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.right--; + } + } + if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + sideMovedIn = 0; + tempSpaceRect.width = r.width; + tempSpaceRect.height = 1; + tempSpaceRect.x = 0; + for (i = 0; i < r.height; i++) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.top++; + sideMovedIn++; + } + } + if (ret.top < baseBounds.top - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.height - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.bottom--; + } + } + if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + } + return ret; + } + + public static function TransformAABBRect(r:Rectangle, m:Matrix) + { + var o1X = r.left; + var o1Y = r.top; + + var o2X = r.right; + var o2Y = r.top; + + var o3X = r.left; + var o3Y = r.bottom; + + var o4X = r.right; + var o4Y = r.bottom; + + var n1X = o1X * m.a + o1Y * m.c + m.tx; + var n1Y = o1X * m.b + o1Y * m.d + m.ty; + + var n2X = o2X * m.a + o2Y * m.c + m.tx; + var n2Y = o2X * m.b + o2Y * m.d + m.ty; + + var n3X = o3X * m.a + o3Y * m.c + m.tx; + var n3Y = o3X * m.b + o3Y * m.d + m.ty; + + var n4X = o4X * m.a + o4Y * m.c + m.tx; + var n4Y = o4X * m.b + o4Y * m.d + m.ty; + + r.left = Math.min(n1X, n2X, n3X, n4X); + r.right = Math.max(n1X, n2X, n3X, n4X); + + r.top = Math.min(n1Y, n2Y, n3Y, n4Y); + r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); + } + } +} diff --git a/job.py b/job.py index 989c991..77c09e8 100644 --- a/job.py +++ b/job.py @@ -3,6 +3,7 @@ import json from validate import * from args import * +import copy asset_src_schema = { "type":"object", @@ -69,19 +70,24 @@ base_path = os.path.join(self.out_dir, self.rel_path) if not os.path.exists(base_path): os.makedirs(base_path) + resource_names = [] for i,r in enumerate(resources): - path = os.path.join(base_path, "%s_%04d.png" % (self.name, i)) + resource_name = "%s_%04d.png" % (self.name, i) if len(resources) > 1 else self.name + ".png" + resource_names.append(resource_name) + path = os.path.join(base_path, resource_name) with open(path, "wb") as f: f.write(base64.b64decode(r)) if len(data) == 1: graphic_and_asset = {} (name, graphic_data) = data.items()[0] - graphic_and_asset = {"data":graphic_data} + graphic_and_asset = {"data":graphic_data, "resources":resource_names} with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps(graphic_and_asset)) else: + write_data = copy.deepcopy(data) + write_data["resources"] = resource_names with open(os.path.join(base_path, self.name + ".asset"), "w") as f: - f.write(pretty_dumps(data)) + f.write(pretty_dumps(write_data)) for name,details in data.iteritems(): with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps({"data":self.name + ".asset"})) diff --git a/old/Checkbox.as b/old/Checkbox.as deleted file mode 100644 index c5aaba2..0000000 --- a/old/Checkbox.as +++ /dev/null @@ -1,42 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - - public class Checkbox extends MovieClip - { - public var Enabled:Boolean = true; - public function Checkbox() - { - checkbox.gotoAndStop(1); - checkbox.addEventListener(MouseEvent.CLICK, Clicked); - } - - protected function Clicked(event) - { - if (!Enabled) return; - Toggle(); - if (OnClick != null) OnClick(OnClickParam); - } - - protected var checked = false; - public function set Checked(value) { checked = value; checkbox.gotoAndStop(checked ? 2 : 1); } - public function get Checked() { return checked; } - - public function set Text(value) { text.text = value; } - - public var OnClickParam; - public var OnClick; - - - public function Toggle() - { - checked = !checked; - checkbox.gotoAndStop(checked ? 2 : 1); - - - } - - } - -} diff --git a/old/GraphicExport-app.xml b/old/GraphicExport-app.xml deleted file mode 100644 index 5144634..0000000 --- a/old/GraphicExport-app.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - GraphicExport - 1.0 - GraphicExport - - GraphicExport - - - GraphicExport.swf - standard - false - true - false - portrait - auto - true - true - true - - - false - false - desktop extendedDesktop diff --git a/old/GraphicExport.exe b/old/GraphicExport.exe deleted file mode 100644 index 56315aa..0000000 --- a/old/GraphicExport.exe +++ /dev/null Binary files differ diff --git a/old/GraphicExport.fla b/old/GraphicExport.fla deleted file mode 100644 index 0b78ed7..0000000 --- a/old/GraphicExport.fla +++ /dev/null Binary files differ diff --git a/old/GraphicExport.swf b/old/GraphicExport.swf deleted file mode 100644 index 542db97..0000000 --- a/old/GraphicExport.swf +++ /dev/null Binary files differ diff --git a/old/NewGraphicDialog.as b/old/NewGraphicDialog.as deleted file mode 100644 index 152011c..0000000 --- a/old/NewGraphicDialog.as +++ /dev/null @@ -1,224 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - import flash.events.*; - import flash.filesystem.File; - import flash.net.FileFilter; - import Defs.GraphicDef; - import flash.text.engine.GraphicElement; - - public class NewGraphicDialog extends MovieClip - { - - public function NewGraphicDialog() - { - // constructor code - Init(); - } - - var typeButtons:Array = new Array(); - - public function Init() - { - graphicPath.text = "Path to Graphic Here"; - - this.removeChild(browseButton); - - var newBrowseButton = new UI_GenericBlueButton(); - newBrowseButton.Text = "Browse"; - newBrowseButton.OnClick = BrowseForFile; - newBrowseButton.x = browseButton.x + (newBrowseButton.width / 2); - newBrowseButton.y = browseButton.y + (newBrowseButton.height / 2); - addChild(newBrowseButton); - - var newTestButton = new UI_GenericBlueButton(); - newTestButton.Text = "Export"; - newTestButton.OnClick = TestFile; - newTestButton.x = testButton.x + (newTestButton.width / 2); - newTestButton.y = testButton.y + (newTestButton.height / 2); - addChild(newTestButton); - - this.removeChild(typePlaceholderButton); - - var typeX = typePlaceholderButton.x; - var typeY = typePlaceholderButton.y + (typePlaceholderButton.height / 2); - - - var typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Graphic (1)"; - typeButton.OnClick = function(){ SetType(1); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Skeletal (3)"; - typeButton.OnClick = function(){ SetType(3); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Scene (6)"; - typeButton.OnClick = function(){ SetType(6); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - animationCheckbox.Checked = true; - //browseButton - //typePlaceholderButton - //usesInput - //usesText.text = "" - } - - var usesInputDefaultText = "Comma Seperated List of Uses Here"; - - public static var fakeID = 9999999; - public function TestFile() - { - fakeID++; - var graphicName = graphicPath.text; - var graphicData = {id:fakeID,graphic:graphicPath.text,v:1,fs:0,p:0,type:selectedType}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new GraphicDef(graphicData); - - this.Hide(); - graphicExport.ExportItem(graphicDef); - } - - var selectedType = 1; - public function SetType(type:Number) - { - selectedType = type; - - for(var i = 0; i < typeButtons.length; i++) - { - typeButtons[i].Enabled = true; - } - - animationCheckbox.visible = false; - - switch(type) - { - case 1: { - typeButtons[0].Enabled = false; - animationCheckbox.visible = true; - break; - } - case 3: typeButtons[1].Enabled = false; break; - case 6: typeButtons[2].Enabled = false; break; - } - } - - var graphicExport:GraphicExport; - public function Show(parentClip) - { - this.graphicExport = parentClip; - - parentClip.addChild(this); - - SetType(selectedType); - - var graphicList = GameData.Instance().GraphicDefines; - - var usesString:String = ""; - var uniqueUseTypes:Array = new Array(); - for (var i = 0; i < graphicList.length; i++) - { - var graphicDef:GraphicDef = graphicList[i]; - var uses = graphicDef.ExportParams['uses']; - for (var usage in uses) - { - if (uniqueUseTypes[uses[usage]] == null) - { - uniqueUseTypes[uses[usage]] = uses[usage]; - usesString += uses[usage] + ", "; - } - } - } - - graphicPath.text = ""; - - } - - public function CloseClicked(event) - { - Hide(); - } - - public function Hide() - { - if (this.parent != null) this.parent.removeChild(this); - } - - public function BrowseForFile() - { - var file:File = new File(); - var swfTypeFilter:FileFilter = new FileFilter("SWF Files","*.swf"); - file.addEventListener(Event.SELECT, openFile); - file.browse([swfTypeFilter]); - } - - private function openFile(event:Event):void - { - _strace(event.target.nativePath); - var path:String = event.target.nativePath; - var pathParts:Array = path.split("Graphics\\"); - if (pathParts.length == 2) - { - var fileRemainder:String = pathParts[1]; - var withoutExtension:String = fileRemainder.split(".")[0]; - var pattern:RegExp = /\\/g; - withoutExtension = withoutExtension.replace(pattern, "/"); - _strace(withoutExtension); - graphicPath.text = withoutExtension; - - if (withoutExtension.indexOf("Backgrounds") > -1) - { - SetType(6); - } - - if (withoutExtension.indexOf("Monsters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Characters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Portraits") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Quest") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Equipment") > -1) - { - SetType(1); - } - - - } - } - - - } - -} diff --git a/old/PNGExportHelper.as b/old/PNGExportHelper.as deleted file mode 100644 index f8c4c9d..0000000 --- a/old/PNGExportHelper.as +++ /dev/null @@ -1,253 +0,0 @@ -package -{ - import flash.display.*; - import com.adobe.images.*; - import flash.utils.*; - import flash.net.*; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import flash.geom.Point; - - public class PNGExportHelper - { - public static var UseExpandedBitmaps = false; - public static var AlphaThreshold = 5; - - private static function ExpandBitmapBorders(bd:BitmapData, bgColor = 0x0, passes = 1):BitmapData - { - /* - var thresh:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - thresh.threshold(bd, bd.rect, new Point(), "<", (20 << 24), bgColor, 0xFF000000, true); - */ - var sampled:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - bd.lock(); - sampled.lock(); - - for (var y = 0; y < bd.height; y++) - { - for (var x = 0; x < bd.width; x++) - { - var oldVal:uint = bd.getPixel32(x, y); - var a:uint = (oldVal & 0xFF000000) >>> 24; - var rgb:uint = (oldVal & 0xFFFFFF); - if (a > AlphaThreshold) - { - sampled.setPixel32(x, y, (0xFF << 24) | rgb); - } - else - { - sampled.setPixel32(x, y, bgColor); - } - } - } - sampled.unlock(); - bd.unlock(); - - return ExpandBitmapBordersInternal(sampled, bgColor, passes); - } - - private static function ExpandBitmapBordersInternal(bd:BitmapData, bgColor, passes):BitmapData - { - var output:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - - var scale = 16; - var scaled:BitmapData = new BitmapData(bd.width/scale, bd.height/scale, true, bgColor); - var mat:Matrix = new Matrix(); - mat.scale(1/scale, 1/scale); - scaled.draw(bd, mat, null, null, null, true); - - output.lock(); - - var colors:Array = new Array(); - var weights:Array = new Array(); - - for (var oy = 0; oy < scaled.height; oy++) - { - - for (var ox = 0; ox < scaled.width; ox++) - { - - var scaledVal:uint = scaled.getPixel32(ox, oy); - var scaleda:uint = (scaledVal & 0xFF000000) >>> 24; - if (scaleda == 0 || scaleda == 255) - { - output.copyPixels(bd, new Rectangle(ox * scale, oy * scale, scale, scale), new Point(ox * scale, oy * scale)); - continue; - } else { - //_strace(scaleda+""); - } - - - for (var y = oy * scale; y < oy * scale + scale; y++) - { - for (var x = ox * scale; x < ox * scale + scale; x++) - { - var oldVal:uint = bd.getPixel32(x, y); - var a:uint = (oldVal & 0xFF000000) >>> 24; - var rgb:uint = (oldVal & 0xFFFFFF); - - if (a == 0 && rgb == bgColor) - { - colors.length = 0; - weights.length = 0; - - for (var y1 = y - 2; y1 <= y + 2; y1++) - { - for (var x1 = x - 2; x1 <= x + 2; x1++) - { - var dist = Math.abs(x1 - x) + Math.abs(y1 - y); - if (dist >= 3) continue; - - if (x1 >= 0 && x1 < bd.width && y1 >= 0 && y1 < bd.height) - { - colors.push(bd.getPixel(x1, y1)); - weights.push(1 - dist * 0.2); - } - } - } - - var newVal = AveragePixels(colors, weights, bgColor); - if (newVal == null) - { - newVal = oldVal; - } - else - { - var newR:uint = (newVal & 0xFF0000) >> 16; - var newG:uint = (newVal & 0xFF00) >> 8; - var newB:uint = (newVal & 0xFF); - - if (newVal != 0 && colors.length >= 4) - { - var bp = true; - } - - var sorted = colors.sort(function(a, b) - { - var aR:uint = (a & 0xFF0000) >> 16; - var aG:uint = (a & 0xFF00) >> 8; - var aB:uint = (a & 0xFF); - - var bR:uint = (b & 0xFF0000) >> 16; - var bG:uint = (b & 0xFF00) >> 8; - var bB:uint = (b & 0xFF); - - var diffA = Math.abs(aR - newR) + Math.abs(aG - newG) + Math.abs(aB - newB); - var diffB = Math.abs(bR - newR) + Math.abs(bG - newG) + Math.abs(bB - newB); - - return diffA - diffB; - - }, Array.RETURNINDEXEDARRAY | Array.DESCENDING); - - var toRemove = Math.min(2, colors.length - 4); - var removed = 0; - for (var i = 0; i < colors.length; i++) - { - var index = sorted.indexOf(i + removed); - if (index < toRemove) - { - colors.splice(i, 1); - weights.splice(i, 1); - removed++; - i--; - if (removed == toRemove) break; - } - } - - var fixOutliersVal = AveragePixels(colors, weights, bgColor); - if (fixOutliersVal == null) newVal = (0xFF << 24) | newVal; - - newVal = (0xFF << 24) | fixOutliersVal; - } - - output.setPixel32(x, y, newVal); - } - else - { - output.setPixel32(x, y, oldVal); - } - } - } - }//end outer scaled x - }//End outer scaled y - - bd.unlock(); - output.unlock(); - - passes--; - if (passes > 0) - { - return ExpandBitmapBordersInternal(output, bgColor, passes); - } - else - { - return output; - } - } - - private static function AveragePixels(colors:Array, weights:Array, bgColor:uint):uint - { - var rTotal = 0; - var gTotal = 0; - var bTotal = 0; - - var wTotal = 0; - - for (var i = 0; i < colors.length; i++) - { - var color:uint = colors[i]; - var a:uint = (color & 0xFF000000) >>> 24; - var rgb:uint = (color & 0xFFFFFF); - - if (a == 0 && rgb == bgColor) - { - colors.splice(i, 1); - weights.splice(i, 1); - i--; - continue; - } - - var r:uint = (rgb & 0xFF0000) >>> 16; - var g:uint = (rgb & 0xFF00) >>> 8; - var b:uint = (rgb & 0xFF); - var w = weights[i]; - - rTotal += w * r; - gTotal += w * g; - bTotal += w * b; - - wTotal += w; - } - - if (wTotal == 0) - { - return null; - } - - rTotal /= wTotal; - gTotal /= wTotal; - bTotal /= wTotal; - - var rFinal = Math.max(0, Math.min(255, Math.round(rTotal))); - var gFinal = Math.max(0, Math.min(255, Math.round(gTotal))); - var bFinal = Math.max(0, Math.min(255, Math.round(bTotal))); - - return (uint(rFinal) << 16) | (uint(gFinal) << 8) | (uint(bFinal)); - } - - - - public static function GetExportPNG(bd:BitmapData):ByteArray - { - if (!UseExpandedBitmaps) return PNGEncoder.encode(bd); - - var expanded:BitmapData = ExpandBitmapBorders(bd, 0x0, 2); - - //var fr:FileReference = new FileReference(); - //fr.save(PNGEncoder.encode(expanded), "output.png"); - - return PNGEncoderWithAlpha.encode(expanded, bd); - } - - } -} \ No newline at end of file diff --git a/old/PreviewHolder.as b/old/PreviewHolder.as deleted file mode 100644 index 587bf68..0000000 --- a/old/PreviewHolder.as +++ /dev/null @@ -1,57 +0,0 @@ -package { - import flash.display.MovieClip; - - public class PreviewHolder extends MovieClip - { - - var startingWidth = 1024; - var startingHeight = 1024; - - public function PreviewHolder() - { - startingWidth = this.width; - startingHeight = this.height; - } - - var clips:Array = new Array(); - public function AddClip(clip) - { - clips.push(clip); - this.addChild(clip); - ArrangeClips(); - } - - public function ArrangeClips() - { - var numCols = Math.ceil(Math.sqrt(clips.length)); - var maxY = 0; - var maxX = 0; - var clipIndex = 0; - for (var row = 0; row < numCols; row++) - { - var clipX = 0; - var clipY = maxY; - for (var col = 0; col < numCols; col++) - { - if (clipIndex == clips.length) break; - clips[clipIndex].x = clipX; - clips[clipIndex].y = clipY; - clipX += clips[clipIndex].width; - var clipBottom = clips[clipIndex].y + clips[clipIndex].height; - if (clipBottom > maxY) maxY = clipBottom; - - var clipRight = clips[clipIndex].x + clips[clipIndex].width; - if (clipRight > maxX) maxX = clipRight; - clipIndex++; - } - } - - var scale = Math.min(startingWidth / maxX, startingHeight / maxY); - if (scale > 1) scale = 1; - - this.scaleX = this.scaleY = scale; - } - - } - -} diff --git a/old/Utils.as b/old/Utils.as deleted file mode 100755 index 02b4f12..0000000 --- a/old/Utils.as +++ /dev/null @@ -1,1202 +0,0 @@ -package old -{ - /* This class has functions similar to the Utils.as in the /flash/Dialogs folder. However, some of - * those functions are different here than in /flash/Dialogs/Utils.as for... reasons? flash folder reasons! - */ - import flash.utils.*; - import flash.net.*; - import flash.display.*; - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.geom.Point; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import flash.geom.ColorTransform; - import fl.motion.Color; - import fl.transitions.Tween; - import fl.transitions.easing.*; - import fl.transitions.TweenEvent; - import flash.net.navigateToURL; - import flash.external.ExternalInterface; - import flash.system.Capabilities; - import flash.filters.*; - import flash.filters.ColorMatrixFilter; - import com.adobe.images.JPGEncoder; - import flash.globalization.DateTimeFormatter; - - import djarts.utils.Base64; - import djarts.utils.PNGEnc; - import User.UserOptions; - - public class Utils - { - //["K","M","B","T","q", "Q", "s", "S","O","N","d","U","D","!","@","#","$","%","^","&","*"] - static var symbols = ["K","M","B","t","q", "Q", "s", "S","o","n","d","U","D","T","Qt","Qd","Sd","St","O","N","v","c"]; - static var divisors = []; - - public static function FormatBigNumber(number:*, round:Boolean=false):String - { - if (number < 0) return '-' + FormatBigNumber(Math.abs(number), round); - - var isWholeNumber = (Math.floor(number) == number); - round = round || isWholeNumber; - - if (number < 1000) - { - if (round) - { - return Math.round(number).toString(); - } - else - { - var decimalPlaces = (number >= 100) ? 1 : 2; // Below 100, show two decimal places. Above, only one. - var roundMult = Math.pow(10, decimalPlaces); - var rounded = Math.round(number); - var bigRounded = Math.round(number * roundMult); - var roundedDifferenceProportion = Math.abs(bigRounded / roundMult - rounded) / rounded; - - if (roundedDifferenceProportion < 0.001) - { - // Not a whole number, but the decimal places aren't worth showing - // Below also handles this, but is slower - return rounded.toString(); - } - else - { - var str:String = bigRounded.toString(); - str = str.substr(0, str.length - decimalPlaces) + "." + str.substr(str.length - decimalPlaces); - - while (str.charAt(str.length - 1) == "0") str = str.substr(0, str.length - 1); //should only ever happen once - if (str.charAt(str.length - 1) == ".") str = str.substr(0, str.length - 1); //probably won't happen at all - - return str; - } - } - } - - // Determine which symbol to use - var power = Math.floor(Math.log(number) / Math.log(1000)); - var index = Math.min(power-1, symbols.length-1); - var amount = number / Math.pow(1000, index+1); - var symbol = (index >= 0 && index < symbols.length) ? symbols[index] : ""; - - // If it's too big for a symbol (or if we just WANT to) - if (amount >= 1000 || UserOptions.ForceScientific) - { - // scientific notation - var power = Math.floor(Math.log(number) / Math.log(10)); - var num = number / Math.pow(10, power); - if (num == 10) { - num = 1; - power += 1; - } - var numString = "" + num; - numString = numString.substr(0, Math.min(4, numString.length)); - return numString + "e" + power; - - } - else - { - // Format with the symbol - // determine number of whole digits (will dictate how many decimals we show) - var whole = Math.floor(amount); - var amount_str:String = String(whole); - - var decimalDivider = 100/Math.pow(10,amount_str.length-1); - - //round to nearest decimal place - amount = int(amount*decimalDivider)/decimalDivider; - - var amountString:String = amount.toString(); - - var noDecimal:String = amountString.replace(".",""); - if (noDecimal.length == 2) - { - if (amountString.indexOf(".") != -1) amountString += "0"; - else amountString += ".0"; - } - else if (noDecimal.length == 1) amountString += ".00"; - - return amountString+symbol; // concat symbol - } - } - - private static var BigNumberRegex = new RegExp(/(\d*),?(\d*)(.*)/); - // Note-DG: This is mostly just used for definitions in the database, that don't require precision. - // This way we can define values in the database as 100B instead of 100000000000. - public static function ParseBigNumberString(number:String):Number - { - var regexArray:Array = BigNumberRegex.exec(number); - var magnitude = symbols.indexOf(regexArray[3]); - var thousands:Number; - if (regexArray[1]) { - thousands = regexArray[1]; - if (regexArray[2]) { // if numbers are split by comma, multiply by 1000 - thousands *= 1000; - } - } else { - thousands = 0; - } - var hundreds:Number = regexArray[2] ? regexArray[2] : 0; - - return (thousands + hundreds) * Math.pow(1000, magnitude + 1); - } - - public static function ParseNumberRange(range:String):Array - { - var split:Array = range.split(','); - return [Number(split[0]), Number(split[1])]; - } - - public static function DesaturateFilter() - { - var desatMatrix:Array = []; - var cmFilter; - - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // red - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // green - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // blue - desatMatrix = desatMatrix.concat([0, 0, 0, 1, 0]); // alpha - cmFilter = new ColorMatrixFilter(desatMatrix); - - return cmFilter; - } - - public static function GetUserAgent():String - { - try - { - var userAgent = ExternalInterface.call("window.navigator.userAgent.toString"); - var browser:String = "[Unknown Browser]"; - - if (userAgent.indexOf("Safari") != -1) - { - browser = "Safari"; - } - if (userAgent.indexOf("Firefox") != -1) - { - browser = "Firefox"; - } - if (userAgent.indexOf("Chrome") != -1) - { - browser = "Chrome"; - } - if (userAgent.indexOf("MSIE") != -1) - { - browser = "Internet Explorer"; - } - if (userAgent.indexOf("Opera") != -1) - { - browser = "Opera"; - } - } - catch (e:Error) - { - //could not access ExternalInterface in containing page - return "[No ExternalInterface]"; - } - - return browser; - } - - public static function GetScreenshot(stage:Stage):String { - var scale:Number = 0.25; - var result:String = null; - var blurFilter:BlurFilter = new BlurFilter(3, 3, BitmapFilterQuality.HIGH); - - var bData:BitmapData = new BitmapData(stage.stageWidth * scale, - stage.stageHeight * scale, false, 0x348400); - var matrix:Matrix = new Matrix(); - matrix.scale(scale, scale); - - bData.draw(stage, matrix); - bData.applyFilter(bData, bData.rect, new Point(0, 0), blurFilter); - - - var imgBytes:ByteArray = new JPGEncoder(80).encode(bData); - //var imgBytes:ByteArray = PNGEnc.encode(bData); - if (imgBytes) { - var screenshotBase64:String = Base64.encode(imgBytes); - if (screenshotBase64) { - result = screenshotBase64; - } - } - - return result; - } - - public static function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function PlayerVersion() - { - - // Get the player's version by using the getVersion() global function. - var versionNumber:String = Capabilities.version; - - // The version number is a list of items divided by "," - var versionArray:Array = versionNumber.split(","); - var length:Number = versionArray.length; - //for(var i:Number = 0; i < length; i++) _strace("versionArray["+i+"]: "+versionArray[i]); - - // The main version contains the OS type too so we split it in two - // and we'll have the OS type and the major version number separately. - var platformAndVersion:Array = versionArray[0].split(" "); - //for(var j:Number = 0; j < 2; j++) _strace("platformAndVersion["+j+"]: "+platformAndVersion[j]); - //_strace("-----"); - - var majorVersion:Number = parseInt(platformAndVersion[1]); - var minorVersion:Number = parseInt(versionArray[1]); - var buildNumber:Number = parseInt(versionArray[2]); - - return Number(majorVersion+"."+minorVersion); - } - - - public static function OpenLocalURLTop(url) - { - navigateToURL(new URLRequest(GameSettings.Approot+url), "_top" ); - } - - public static function OpenLocalURL(url) - { - navigateToURL(new URLRequest(GameSettings.Approot+url), "_blank" ); - } - - public static function OpenURL(url, window = "_blank") - { - navigateToURL(new URLRequest(url), window); - } - - public static var ExitFullScreenCallback; - - public static function WallPublish(title:String, desc1:String, desc2:String, image:String, url = null, action = null) - { - if (Utils.ExitFullScreenCallback) Utils.ExitFullScreenCallback(); - //_strace(title + "\n" + desc1 + "\n" + desc2 + "\n" + image + "\n"); - ExternalInterface.call("askToPublish", title, url, desc1, desc2, image, action); - - //if (Settings.Platform == Settings.HI5) { - //DialogManager.Instance().ShowMessageBox("The message was posted to your wall!", "", "OK", null); - //} - } - - public static function SendToRecipients(recipients:Array, description, data) - { - if (!GameSettings.IsFacebook) return; - - if (Utils.ExitFullScreenCallback) Utils.ExitFullScreenCallback(); - try { - ExternalInterface.call("sendToRecipients", recipients, description ,data); - } - catch (e) - { - _strace(e.message); - } - } - - - public static function GetFriendData() - { - try { - return ExternalInterface.call("pollInviteData"); - } - catch (e) - { - _strace(e.message); - } - } - - - public static function singleBounceEase(t:Number, b:Number, c:Number, d:Number):Number - { - t = t / d; - if (t < 0.7) { - t *= 1.0 / 0.65; - return c * (t * t) + b; - } - return c * (t * t) + b; - } - - public static function Finish(e:TweenEvent) - { - //_strace("done " + e.currentTarget.obj.x + " " + e.currentTarget.obj.y + " " + e.currentTarget.obj.scaleX + " " + e.currentTarget.obj.scaleY); - e.currentTarget.removeEventListener(TweenEvent.MOTION_FINISH, Finish); - } - public static function Popup(mc, startScale = 0.8, finishCallback = null) - { - var rect:Rectangle = mc.getRect(mc); - var targetX = mc.x; - var targetY = mc.y; - var centerX = mc.x + rect.left + mc.width / 2.0; - var centerY = mc.y + rect.top + mc.height / 2.0; - var startX = centerX - (rect.left + mc.width / 2.0) * startScale; - var startY = centerY - (rect.top + mc.height / 2.0) * startScale; - var tweenSX = new Tween(mc, "scaleX", singleBounceEase, startScale, 1.0, 4, false); - if (finishCallback) tweenSX.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenSY = new Tween(mc, "scaleY", singleBounceEase, startScale, 1.0, 4, false); - if (finishCallback) tweenSY.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenX = new Tween(mc, "x", singleBounceEase, startX, targetX, 4, false); - if (finishCallback) tweenX.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenY = new Tween(mc, "y", singleBounceEase, startY, targetY, 4, false); - if (finishCallback) tweenY.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - return [tweenSX, tweenSY, tweenX, tweenY]; - } - public static function StringSplit(s:String, delim:String, max:int = -1):Array - { - var ret:Array = s.split(delim); - if (max != -1) { - var more:String = ret.slice(max - 1).join(delim); - ret.splice(max - 1); - ret[max - 1] = more; - } - return ret; - } - - public static function StringStartsWith(str:String, substr:String):Boolean - { - if (substr.length > str.length) return false; - return (str.substr(0, substr.length) == substr); - } - - public static function StringEndsWith(str:String, substr:String):Boolean - { - if (substr.length > str.length) return false; - return (str.substr(str.length - substr.length, substr.length) == substr); - } - - public static function StringContains(str:String, substr:String):Boolean - { - return (str.indexOf(substr) !== -1); - } - - private static var vowelsAndH = { - "a":true, "A":true, - "e":true, "E":true, - "i":true, "I":true, - "o":true, "O":true, - "u":true, "U":true, - "h":true, "H":true - } - public static function StringStartsWithVowelOrH(s:String):Boolean - { - if (vowelsAndH[s.charAt(0)]) return true; - return false; - } - - public static function CopyObject(obj, except = null) - { - var i; - if (except == null) except = []; - if (obj is Array) { - var obj2 = []; - for (i = 0; i < obj.length; i++) { - obj2.push(Utils.CopyObject(obj[i])); - } - return obj2; - } - var ret:Object = {}; - for (i in obj) - { - if (except.indexOf(i) == -1) { - ret[i] = obj[i]; - } - } - - return ret; - } - public static function CopyToObject(objFrom, objTo, except = null) - { - if (except == null) except = []; - for (var i in objFrom) - { - if (except.indexOf(i) == -1) { - objTo[i] = objFrom[i]; - } - } - } - public static function CopyToObjectOnly(objFrom, objTo, only) - { - if (only == null) return; - for (var i in only) - { - if (objFrom.hasOwnProperty(only[i])) - { - objTo[only[i]] = objFrom[only[i]]; - } - } - } - - public static function ColorizeRGB(clip:MovieClip, r:int,g:int,b:int) - { - var cTransform = clip.transform.colorTransform; - cTransform.redOffset = r; - cTransform.greenOffset = g; - cTransform.blueOffset = b; - clip.transform.colorTransform = cTransform; - } - - public static function hex2rgb (hex):Object - { - var red = hex>>16; - var greenBlue = hex-(red<<16) - var green = greenBlue>>8; - var blue = greenBlue - (green << 8); - return({r:red, g:green, b:blue}); - } - - public static function RGBtoHEX(r, g, b) { - return r << 16 | g << 8 | b; - } - - /** - * NOTE: An alpha of 1 will make the object a solid color (good for silhouettes) - */ - public static function TintDisplayObject(obj:DisplayObject, color:uint = 0xffffff, alpha:Number = 1.0) - { - var cTint:Color = new Color(); - cTint.setTint(color, alpha); - obj.transform.colorTransform = cTint; - } - - // given an origin (ox, oy) and a look at point (tx, ty), - // and a clip with the given number of rotation states, which - // rotation should we pick? - public static function Rotation(ox, oy, tx, ty, rotations) - { - var delta:Point = new Point(tx - ox, ty - oy); - if (Point.distance(delta, new Point(0.0, 0.0)) < 0.00001) { - delta.y = -1.0; - } - var d = ( - (-Math.floor( - /* calculate the rotation and scale it */ - Math.atan2(delta.y, delta.x) / (Math.PI * 2.0) * rotations - + 0.5 // add 0.5 and take the floor (round to closest int) - ) - + rotations) // atan2 returns in the range -pi to pi, measured ccw from +x, - // we negate it and add rotations again to get it in the range - // [0, rotations] - % rotations) + 1; // add 1 to reference frames - return d; - } - /* performs multiple operations asynchronously, but wait for them all to finish: - * instead of calling a bunch of functions and passing callbacks, pass those callbacks to WaitForFunctions - * and use ret.callbacks[0], ret.callbacks[1], etc... as the callbacks - * this will wait until every command is complete and call all the callbacks at once. - * - * For instance, to load multiple graphics packs asynchronously and wait for them all to finish, - * call var ret = WaitForFunctions([DoneLoading, null, null, null]); to generate - * ret.callbacks[0]..ret.callbacks[3], and pass these to 4 calls to LoadExternalGraphics. - * When these 4 calls complete, the provided 4 functions will be called with the arguments returned - * from the callbacks (in this case, only DoneLoading will be called since the - * other callbacks are null). - */ - public static function WaitForFunctions(...funcs):Object - { - var ret:Object = {}; - // has a callback been hit? - ret.hit = new Array(funcs.length); - // what were the original arguments the callback was called with - ret.args = new Array(funcs.length); - // a list of the artifical callbacks we are providing - ret.callbacks = new Array(funcs.length); - // the real callbacks - ret.funcs = funcs; - ret.done = false; - - ret.immediate = []; - - for (var i = 0; i < funcs.length; i++) { - // we have to setup this temp callback in another function, because the anon function's - // activation object will contain the current scope, meaning that the variable - // i will be updated in each function; if we do it in a seperate function each - // activation object will reference a different i - ret.callbacks[i] = Utils.SetupFunction(ret, i); - } - return ret; - } - - /** - * Returns the standard money format for an integer amount - */ - public static function FormatCurrency(amount:int, symbol:String = "$"):String - { - var afterDecimal:String = (amount % 100).toString(); - while (afterDecimal.length < 2) afterDecimal = "0" + afterDecimal; //mmmm string concatenation - - var beforeDecimal:String; - if (amount > 100) - { - beforeDecimal = Math.floor(amount/100).toString(); - } - else - { - beforeDecimal = "0"; - } - - return symbol + beforeDecimal + "." + afterDecimal; - } - - public static function FormatNumber(amount){ - var whole = Math.floor(amount); - // convert the number to a string - var amount_str:String = String(whole); - var total_str:String = String(amount); - - var number_array:Array = []; - var start:Number; - var end:Number = amount_str.length; - while (end > 0) { - start = Math.max(end - 3, 0); - number_array.unshift(amount_str.slice(start, end)); - end = start; - } - - var point = total_str.indexOf("."); - - var ret = number_array.join(","); - if (point != -1 && point < total_str.length) - { - ret += total_str.substr(point); - } - - return ret; - } - - protected static function SetupFunction(ret, i):Function - { - var a:Function = - function(...rest) { - if (ret.immediate[i]) ret.immediate[i].apply(null, rest); - ret.hit[i] = true; - ret.args[i] = rest; - var ok:Boolean = true; - var j; - for (j = 0; j < ret.hit.length; j++) { - if (!ret.hit[j]) { ok = false; break; } - } - if (ok && !ret.done) { - ret.done = true; - for (j = 0; j < ret.funcs.length; j++) { - if (ret.funcs[j] != null) ret.funcs[j].apply(null, ret.args[j]); - } - } - }; - return a; - } - - // useful for the paned dialogs to show a certain pane/button - public static function OnlyVisible(obj, set:Array, index:int) - { - for (var i in set) { - if (i != index) { - obj[set[i]].visible = false; - } else { - obj[set[i]].visible = true; - } - } - } - public static function AllVisible(obj, set:Array) - { - for (var i in set) { - obj[set[i]].visible = true; - } - } - // set one of a list of tabs to be enabled - public static function OnlyToggled(obj, set:Array, index:int) - { - for (var i in set) { - if (i != index) { - obj[set[i]].SetToggled(false); - } else { - obj[set[i]].SetToggled(true); - } - } - } - // get the frame number of a label in the timeline - public static function GetLabelFrame(mc, name:String):int - { - for (var l in mc.currentLabels) { - if (mc.currentLabels[l].name == name) return mc.currentLabels[l].frame; - } - return 1; - } - // generate a quick text field of a certain color/style - public static function BasicTextField(color:uint, - size:int, - font:String, - text:String, - additional:Object = null, - align = "left"):TextField - { - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.align = align; - if (additional != null) for (var a in additional) f[a] = additional[a]; - f.font = font; - f.color = color; - f.size = size; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.text = text; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - return t; - } - public static function var_dump(_obj, name = "Dump") - { - _strace(name + " " + (_obj) + " {"); - flash.utils.describeType(_obj); - var varList:XMLList = flash.utils.describeType(_obj)..variable; - - for(var i:int; i < varList.length(); i++) - { - //Show the name and the value - _strace(" " + varList[i].@name+' = '+ _obj[varList[i].@name]); - } - _strace("}"); - } - - public static function SetChildFrames(parentClip, frame, exclude = null) - { - if (parentClip is MovieClip && parentClip.name != exclude) - { - parentClip.gotoAndStop(frame); - for (var i = 0; i < parentClip.numChildren; i++) - { - Utils.SetChildFrames(parentClip.getChildAt(i), frame, exclude); - } - } - } - - public static function SetChildFramesNoParent(parentClip, frame, exclude = null) - { - if (parentClip is MovieClip && parentClip.name != exclude) - { - for (var i = 0; i < parentClip.numChildren; i++) - { - Utils.SetChildFrames(parentClip.getChildAt(i), frame, exclude); - } - } - } - - //modifies the array passed as parameter, following the MO of the built in Array.sort() - public static function insertionSort(array:Array, compareFunction:Function):void - { - for(var i:int=1; i < array.length; i++) - { - var value:Object = array[i]; - var k:int=i-1; - while( k >= 0 && compareFunction(array[k], value) == -1) - { - array[k+1]=array[k]; - k--; - } - array[k+1]=value; - } - } - - - public static function Screenshot(sourceClip, receiverURL, filename) - { - - var jpgSource:BitmapData; - - if (sourceClip is Stage) - { - jpgSource = new BitmapData (sourceClip.stageWidth, sourceClip.stageHeight); - } else { - jpgSource = new BitmapData (sourceClip.width, sourceClip.height); - } - - jpgSource.draw(sourceClip); - - var jpgEncoder:JPGEncoder = new JPGEncoder(85); - var jpgStream:ByteArray = jpgEncoder.encode(jpgSource); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - var jpgURLRequest:URLRequest = new URLRequest(receiverURL+"?name="+filename); - jpgURLRequest.requestHeaders.push(header); - jpgURLRequest.method = URLRequestMethod.POST; - jpgURLRequest.data = jpgStream; - navigateToURL(jpgURLRequest, "_blank"); - - } - - - public static function SetColors(clip, color) - { - var colorTransform:ColorTransform; - - if (clip == null || color == null) return; - - if (clip.hasOwnProperty("outline") && clip.outline != null) - { - colorTransform = clip.outline.transform.colorTransform; - colorTransform.color = color.Outline; - clip.outline.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryOutline") && clip.secondaryOutline != null) - { - colorTransform = clip.secondaryOutline.transform.colorTransform; - colorTransform.color = color.LightOutline; - clip.secondaryOutline.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("color") && clip.color != null) - { - colorTransform = clip.color.transform.colorTransform; - colorTransform.color = color.Primary; - clip.color.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryColor") && clip.secondaryColor != null) - { - colorTransform = clip.secondaryColor.transform.colorTransform; - colorTransform.color = color.Secondary; - clip.secondaryColor.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("shadow") && clip.shadow != null) - { - colorTransform = clip.shadow.transform.colorTransform; - colorTransform.color = color.Shadow; - clip.shadow.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryShadow") && clip.secondaryShadow != null) - { - colorTransform = clip.secondaryShadow.transform.colorTransform; - colorTransform.color = color.SecondaryShadow; - clip.secondaryShadow.transform.colorTransform = colorTransform; - } - } - /* returns a rect with the x, and y pos to center and the scaleX and scaleY as width and height */ - public static function GetUniformScaleRect(clip:MovieClip, maxWidth, maxHeight) - { - var rect:Rectangle = new Rectangle(0,0,0,0); - - var widthScale = Math.min(maxWidth / clip.width, 999); - var heightScale = Math.min(maxHeight / clip.height, 999); - - var scale = 1; - if (widthScale > heightScale) - { - scale = heightScale; - } else { - scale = widthScale; - } - - rect.width = clip.width * scale; - rect.height = clip.height * scale; - - var pb = clip.getBounds(clip); - var xadjust = -pb.left * scale; - var yadjust = -pb.top * scale; - - rect.x = xadjust + (maxWidth - rect.width) / 2; - rect.y = yadjust + (maxHeight - rect.height) / 2; - - rect.width = scale; - rect.height = scale; - - return rect; - } - - public static function Dec2Hex(d) - { - var chars:String = "0123456789ABCDEF"; - var str:String = ""; - while (d > 0 || str.length < 2) - { - var digit = d % 16; - d = (d - digit) / 16; - str = chars.charAt(digit) + str; - } - return str; - } - - public static function Hex2Dec(h:String) - { - var chars:String = "0123456789ABCDEF"; - var val = 1; - var res = 0; - for (var i = h.length - 1; i >= 0; i--) - { - res += chars.indexOf(h.substr(i, 1)) * val; - val *= 16; - } - return res; - } - - public static function ShallowCopyArray(array:Array) - { - if (!array) return null; - - var newArray:Array = []; - for (var i:int = 0; i < array.length; i++) - { - newArray.push(array[i]); - } - return newArray; - } - - /* Note: Will fail if any items in either array have reference type semantics (unless they point to the same object) - * (as opposed to value type semantics) - */ - public static function areEqual(a:Array,b:Array):Boolean { - if(a.length != b.length) { - return false; - } - var len:int = a.length; - for(var i:int = 0; i < len; i++) { - if(a[i] !== b[i]) { - return false; - } - } - return true; - } - - /* Note: Will fail if any items in either array have reference type semantics - * (as opposed to value type semantics) - */ - public static function objectsAreEqual(a:Object,b:Object):Boolean { - - for (var i in a) - { - if (!b.hasOwnProperty(i) || a[i] != b[i]) return false; - } - - return true; - } - - public static function DeepCopyClone (source : Object) : * - { - var array : ByteArray = new ByteArray (); - - array.writeObject (source); - array.position = 0; - - return array.readObject (); - } - - // {a:1, b:2} => [1,2] - public static function ObjectValues (obj:Object):Array { - var array = []; - for (var key in obj) array.push(obj[key]); - return array; - } - - // {a:1, b:2} => ["a","b"] - public static function ObjectKeys (obj:Object):Array { - var array = []; - for (var key in obj) array.push(key); - return array; - } - - // normal random variate generator; mean m, standard deviation s - public static function BoxMullerRandomNormal(m:Number, s:Number) : Number - { - var x1, x2, w, y1:Number; - var y2:Number; - var use_last:Boolean = false; - - if (use_last == true) /* use value from previous call */ - { - y1 = y2; - use_last = false; - } - else - { - do { - x1 = 2.0 * Math.random() - 1.0; - x2 = 2.0 * Math.random() - 1.0; - w = x1 * x1 + x2 * x2; - } while ( w >= 1.0 ); - - w = Math.sqrt( (-2.0 * Math.log( w ) ) / w ); - y1 = x1 * w; - y2 = x2 * w; - use_last = true; - } - - return( m + y1 * s ); - } - - public static function SanitizeNumber(n) - { - if (n is Number) - { - if (n == Number.NEGATIVE_INFINITY || n == Number.POSITIVE_INFINITY || n == Number.NaN) return 0; - } - return n; - } - - public static function IsNumberInvalid(n) - { - if (n is Number) - { - if (n == Number.NEGATIVE_INFINITY || n == Number.POSITIVE_INFINITY || n == Number.NaN) return true; - } - return false; - } - - public static function LimitNumberToMax(n) - { - if (n == Number.POSITIVE_INFINITY) return Number.MAX_VALUE; - return n; - } - - /* - value= Math.round(20/7); - value= int((20/7)*10)/10; - value= int((20/7)*100)/100; - value= int((20/7)*1000)/1000; - value= int((20/7)*10000)/10000; - */ - public static function RoundToDecimalPlaces(number:Number, places:int) - { - return Math.round((number)*Math.pow(10,places))/Math.pow(10,places); - } - - public static function GetShuffledArray(a:Array) : Array - { - var r:Array = a.concat(); - r.sort(randomSort); - return r; - } - - ///Convenience function since I keep forgetting the name of randomSort (hint: it's randomSort) - public static function ShuffleArray(a:Array) - { - a.sort(randomSort); - } - - public static function PickRandom(a:Array) - { - return a[Math.floor(Math.random() * a.length)]; - } - - /** - * Returns n elements of array a, up to a maximum of a's length. - * If forceCopy is set, the returned array will always be a new instance. - */ - public static function PickRandomSet(a:Array, n:int, forceCopy:Boolean=false):Array - { - if (a.length <= n || a.length == 0) - { - if (forceCopy) return a.concat(); - else return a; - } - if (n == 1) return [PickRandom(a)]; - - var shuffled:Array = GetShuffledArray(a); - return shuffled.slice(0, n); - } - - /** - * Does not randomly sort an array! To do that, Use the default array.sort with this as its argument. - * If you want a new, shuffled array, use GetShuffledArray - */ - public static function randomSort(a:*, b:*) : Number - { - if (Math.random() < 0.5) return -1; - else return 1; - } - - /** - * Returns the union of arr1 and arr2. If the elements are not primitive types, you'll need to provide a sorting function. - * If inPlace, a1 and a2 will be sorted. - * If they already contain duplicates, then all bets are off. - */ - public static function MergeArrays(arr1:Array, arr2:Array, sortFunc:Function = null, inPlace:Boolean = false) : Array - { - var ret:Array = []; - var a1:Array = (inPlace) ? arr1 : arr1.slice(); - var a2:Array = (inPlace) ? arr2 : arr2.slice(); - - var len1:uint = a1.length; - var len2:uint = a2.length; - var i1:uint = 0; - var i2:uint = 0; - - //Boring cases - if (len1 == 0 && len2 == 0) return ret; - if (len1 == 0) return (inPlace) ? a2.slice() : a2; - if (len2 == 0) return (inPlace) ? a1.slice() : a1; - - if (sortFunc) - { - a1.sort(sortFunc); - a2.sort(sortFunc); - } - else - { - a1.sort(); - a2.sort(); - } - - while (i1 < len1) - { - //add all from a2 up to a1[i1] - while (i2 < len2 && a2[i2] <= a1[i1]) - { - ret.push(a2[i2]); - i2 += 1; - } - if (ret.length == 0 || a1[i1] != ret[ret.length-1]) ret.push(a1[i1]); - i1 += 1; - } - - while (i2 < len2) ret.push(a2[i2]); - - return ret; - } - - public static function ConvertToHHMMSS(seconds:Number):String - { - var s:Number = seconds % 60; - var m:Number = Math.floor((seconds % 3600 ) / 60); - var h:Number = Math.floor(seconds / (60 * 60)); - - var hourStr:String = (h == 0) ? "" : DoubleDigitFormat(h) + ":"; - var minuteStr:String = DoubleDigitFormat(m) + ":"; - var secondsStr:String = DoubleDigitFormat(s); - - return hourStr + minuteStr + secondsStr; - } - - public static function DoubleDigitFormat(num:uint):String - { - if (num < 10) - { - return ("0" + num); - } - return String(num); - } - - public static function CapitolizeString(str:String) : String - { - var firstChar:String = str.substr(0, 1); - var restOfString:String = str.substr(1, str.length); - - return firstChar.toUpperCase()+restOfString.toLowerCase(); - } - - // ^ Nice spelling, goof! - public static function CapitalizeString(str:String) : String - { - return CapitolizeString(str); - } - - public static function GetListString(listStrings:Array) : String - { - var andString:String = "&"; - var count:int = 0; - - var listString:String = ""; - for (var i = 0; i < listStrings.length; i++) - { - if (count > 0 && listStrings.length == 2) listString += " "+andString+" "; // For just 2 items - else if (count == listStrings.length-1 && listStrings.length > 2) - { - // For adding "and" at the end of 3+ items. It is: ", and $(item)" - var endingString:String = ""; - endingString = endingString.replace("$(item)", listStrings[i]); - listString += endingString; - count++; - continue; - } - else if (count > 0) listString += ", "; // Comma separated list - - listString += listStrings[i]; - count++; - } - - return listString; - } - - /* - * Flash doesn't like the way MySQL prints dates (2016-06-02 13:00:00) - * "The year month and day terms can be separated by a forward slash (/) or by spaces, but never by a dash (-)." - */ - public static function ParseDate (dateString:String) : Date - { - var pattern:RegExp = /-/g; - var date = new Date(); - dateString = dateString.replace(pattern, "/"); - date.setTime(Date.parse(dateString)); - return date; - } - - /* - * For display only, not intended to be read by ParseDate - * Tuesday, June 7th, 2016 at 10:32 AM - */ - public static function FormatDate (date:Date) : String - { - var f:DateTimeFormatter = new DateTimeFormatter("en-US"); - var dateStr:String; - var lastChar:String; - - //Flash can't do "1st", "2nd", etc - - f.setDateTimePattern("d"); - dateStr = f.format(date); - lastChar = dateStr.charAt(dateStr.length - 1); - - if (lastChar == "1" && dateStr != "11") dateStr += "st"; - else if (lastChar == "2" && dateStr != "12") dateStr += "nd"; - else if (lastChar == "3" && dateStr != "13") dateStr += "rd"; - else dateStr += "th"; - - f.setDateTimePattern("EEEE, MMMM '" + dateStr + "', yyyy 'at' h:mm a"); - return f.format(date); - } - - /* Simply counts the number of properties on the object - */ - public static function CountObjectParameters(obj:Object):int - { - var cnt:int=0; - - for (var s:String in obj) cnt++; - - return cnt; - } - - /** - * For when shit gets real - */ - public static function PrintStackTrace() - { - try { - throw new Error('StackTrace'); - } catch (e:Error) { - _strace(e.getStackTrace()); - } - } - } -} \ No newline at end of file diff --git a/org/aszip/compression/CompressionMethod.as b/org/aszip/compression/CompressionMethod.as deleted file mode 100644 index 42fe7a0..0000000 --- a/org/aszip/compression/CompressionMethod.as +++ /dev/null @@ -1,17 +0,0 @@ -package org.aszip.compression - -{ - - /** - * The CompressionMethod class lets you choose the compression algorithms used for the files in the ZIP. - */ - public class CompressionMethod - - { - - public static var GZIP:String = 'GZIP'; - public static var NONE:String = 'NONE'; - - } - -} \ No newline at end of file diff --git a/org/aszip/crc/CRC32.as b/org/aszip/crc/CRC32.as deleted file mode 100644 index fcbc4f0..0000000 --- a/org/aszip/crc/CRC32.as +++ /dev/null @@ -1,63 +0,0 @@ -/** -* AS3 CRC32 algorithm implementation -*/ - -package org.aszip.crc -{ - - import flash.utils.ByteArray; - - public class CRC32 { - - private var crc32:int; - private static var CRCTable:Array = initLookupTable(); - - private static function initLookupTable ():Array - { - - var polynomial:int = 0xEDB88320; - var CRC32Table:Array = new Array(256); - - var i:int = 256; - var j:int = 8; - - while ( i-- ) - - { - - var crc:int = i; - - while ( j-- ) crc = (crc & 1) ? (crc >>> 1) ^ polynomial : (crc >>> 1); - - j = 8; - - CRC32Table [ i ] = crc; - - } - - return CRC32Table; - - } - - public function generateCRC32 ( pBytes:ByteArray ):void - { - - var length:int = pBytes.length; - - var crc:int = ~crc32; - - for ( var i:int = 0; i < length; i++ ) crc = ( crc >>> 8 ) ^ CRCTable[ pBytes[i] ^ (crc & 0xFF) ]; - - crc32 = ~crc; - - } - - public function getCRC32 ():int - { - - return crc32 & 0xFFFFFFFF; - - } - - } -} \ No newline at end of file diff --git a/org/aszip/encoding/PNGEnc.as b/org/aszip/encoding/PNGEnc.as deleted file mode 100644 index 9847cd6..0000000 --- a/org/aszip/encoding/PNGEnc.as +++ /dev/null @@ -1,218 +0,0 @@ -/** -* PNG encoding class from kaourantin.net, optimised by 5etdemi.com/blog -* @author kaourantin -* @version 0.1 -*/ - -package org.aszip.encoding -{ - import flash.utils.ByteArray; - import flash.display.BitmapData; - import flash.utils.getTimer; - import flash.geom.Rectangle; - - public class PNGEnc { - - public static function encode(img:BitmapData, type:uint = 0):ByteArray { - - - - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - if(img.transparent || type == 0) - { - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - } - else - { - IHDR.writeUnsignedInt(0x08020000); //24bit RGB - } - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - - switch(type) - { - case 0: - writeRaw(img, IDAT); - break; - case 1: - writeSub(img, IDAT); - break; - } - - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - - - - return png; - } - - private static function writeRaw(img:BitmapData, IDAT:ByteArray):void - { - var h:int = img.height; - var w:int = img.width; - var transparent:Boolean = img.transparent; - - for(var i:int=0;i < h;i++) { - // no filter - if ( !transparent ) { - var subImage:ByteArray = img.getPixels( - new Rectangle(0, i, w, 1)); - //Here we overwrite the alpha value of the first pixel - //to be the filter 0 flag - subImage[0] = 0; - IDAT.writeBytes(subImage); - //And we add a byte at the end to wrap the alpha values - IDAT.writeByte(0xff); - } else { - IDAT.writeByte(0); - var p:uint; - for(var j:int=0;j < w;j++) { - p = img.getPixel32(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - (p>>>24))); - } - } - } - } - - private static function writeSub(img:BitmapData, IDAT:ByteArray):void - { - var r1:uint; - var g1:uint; - var b1:uint; - var a1:uint; - - var r2:uint; - var g2:uint; - var b2:uint; - var a2:uint; - - var r3:uint; - var g3:uint; - var b3:uint; - var a3:uint; - - var p:uint; - var h:int = img.height; - var w:int = img.width; - - for(var i:int=0;i < h;i++) { - // no filter - IDAT.writeByte(1); - if ( !img.transparent ) { - r1 = 0; - g1 = 0; - b1 = 0; - a1 = 0xff; - for(var j:int=0;j < w;j++) { - p = img.getPixel(j,i); - - r2 = p >> 16 & 0xff; - g2 = p >> 8 & 0xff; - b2 = p & 0xff; - - r3 = (r2 - r1 + 256) & 0xff; - g3 = (g2 - g1 + 256) & 0xff; - b3 = (b2 - b1 + 256) & 0xff; - - IDAT.writeByte(r3); - IDAT.writeByte(g3); - IDAT.writeByte(b3); - - r1 = r2; - g1 = g2; - b1 = b2; - a1 = 0; - } - } else { - r1 = 0; - g1 = 0; - b1 = 0; - a1 = 0; - for(var k:int=0;k < w;k++) { - p = img.getPixel32(k,i); - - a2 = p >> 24 & 0xff; - r2 = p >> 16 & 0xff; - g2 = p >> 8 & 0xff; - b2 = p & 0xff; - - r3 = (r2 - r1 + 256) & 0xff; - g3 = (g2 - g1 + 256) & 0xff; - b3 = (b2 - b1 + 256) & 0xff; - a3 = (a2 - a1 + 256) & 0xff; - - IDAT.writeByte(r3); - IDAT.writeByte(g3); - IDAT.writeByte(b3); - IDAT.writeByte(a3); - - r1 = r2; - g1 = g2; - b1 = b2; - a1 = a2; - } - } - } - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - for (var n:uint = 0; n < 256; n++) { - //var c:uint = n; - for (var k:uint = 0; k < 8; k++) { - if (n & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - var c:uint = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - 0xff] ^ (c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/flash/util/RectangleNode.as b/flash/util/RectangleNode.as new file mode 100644 index 0000000..6f31e44 --- /dev/null +++ b/flash/util/RectangleNode.as @@ -0,0 +1,178 @@ +package util { + import flash.geom.Rectangle; + + public class RectangleNode + { + public var Left:RectangleNode = null; + public var Right:RectangleNode = null; + public var Rect:Rectangle = null; + public var InUse:Boolean = false; + public var Removed:Boolean = false; + public var Parent:RectangleNode = null; + public var AllocationID = 0; + public var Host:RectanglePacker= null; + public var MinAllocationID = 0; + public var NodeID; + public static var NextNodeID = 0; + + public var DontRemove = false; + + public var LastAccessTime = 0; + + public var Flags = []; + + public var UpdateTo:RectangleNode = null; + + /* + public function get Removed() + { + return _Removed; + } + + public function set Removed(r) + { + this._Removed = r; + } + + public function get Host():RectanglePacker + { + return _Host; + } + public function set Host(p:RectanglePacker) + { + this._Host = p; + + if (_Left && _Left.Host != p) + { + throw new Error("bad left host"); + } + if (_Right && _Right.Host != p) + { + throw new Error("bad right host"); + } + if (_Parent && _Parent.Host != p) + { + throw new Error("bad parent host"); + } + + } + + public function get Left():RectangleNode + { + return _Left; + } + public function set Left(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad left host"); + } + _Left = n; + } + public function get Right():RectangleNode + { + return _Right; + } + public function set Right(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad right host"); + } + _Right = n; + } + + public function get Parent():RectangleNode + { + return _Parent; + } + public function set Parent(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad parent host"); + } + _Parent = n; + } + */ + public function get IsFreeSpace() + { + return Left == null && Right == null && !InUse; + } + public function UpdateLinksFromNode(node:RectangleNode) + { + if (node.Parent) + { + if (node.Parent.Left == node) + { + node.Parent.Left = this; + } + if (node.Parent.Right == node) + { + node.Parent.Right = this; + } + } + if (node.Left) + { + node.Left.Parent = this; + } + if (node.Right) + { + node.Right.Parent = this; + } + } + public function MakeFromNode(node:RectangleNode) + { + //_Host = node.Host; + Host = node.Host; + Left = node.Left; + Right = node.Right; + Parent = node.Parent; + AllocationID = node.AllocationID; + InUse = node.InUse; + MinAllocationID = node.MinAllocationID; + NodeID = node.NodeID; + Rect = node.Rect.clone(); + Removed = node.Removed; + DontRemove = node.DontRemove; + } + public function RectangleNode(x, y, w, h, host:RectanglePacker) + { + this.NodeID = NextNodeID++; + this.Host = host; + this.Rect = new Rectangle(x, y, w, h); + } + public function OutputJSON() + { + var node = {}; + node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; + node.in_use = InUse; + node.id = NodeID; + if (this.Left) node.left = this.Left.OutputJSON(); + if (this.Right) node.right = this.Right.OutputJSON(); + return node; + } + + public function ReadJSON(details) + { + details.new_node = this; + this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); + this.Removed = false; + + this.InUse = details.in_use; + + if (details.hasOwnProperty("right")) + { + this.Right = new RectangleNode(0, 0, 0, 0, this.Host); + Right.ReadJSON(details.right); + Right.Parent = this; + } + if (details.hasOwnProperty("left")) + { + this.Left = new RectangleNode(0, 0, 0, 0, this.Host); + Left.ReadJSON(details.left); + Left.Parent = this; + } + } + } +} diff --git a/flash/util/RectanglePacker.as b/flash/util/RectanglePacker.as new file mode 100644 index 0000000..597d7fd --- /dev/null +++ b/flash/util/RectanglePacker.as @@ -0,0 +1,562 @@ +package util { + import flash.geom.*; + import flash.display.BitmapData; + import flash.display.MovieClip; + import flash.text.TextField; + import flash.events.*; + import flash.sampler.StackFrame; + + public class RectanglePacker + { + protected var w:int; + protected var h:int; + protected var root:RectangleNode; + public var NextAllocationID = 0; + + public function get width():int { return w; } + public function get height():int { return h; } + + public function RectanglePacker(w, h) + { + this.w = w; + this.h = h; + root = new RectangleNode(0, 0, w, h, this); + root.AllocationID = -1; + } + protected var area = 0; + + protected var testRender:MovieClip = new MovieClip(); + + public function GetRoot():RectangleNode + { + return root; + } + + public function GetLeafNodes():Array + { + return GetLeafNodesInternal(root); + } + + protected function GetLeafNodesInternal(n:RectangleNode):Array + { + if (n.InUse) return [n]; + var ret:Array = new Array(); + if (n.Left) ret = GetLeafNodesInternal(n.Left); + if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); + return ret; + } + + public function GetUsedArea() + { + return area; + } + + public function get efficiency() + { + return area / (w * h); + } + + protected function RectCost(w, h) + { + if (w == 0 || h == 0) return 99999999; + return (Math.max(w, h) / Math.min(w, h)) * w * h; + } + + protected function EnumerateTree(r:RectangleNode = null, indent = "") + { + if (r == null) r = this.root; + var str = ""; + str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; + if (r.Left) str += EnumerateTree(r.Left, indent + " "); + if (r.Right) str += EnumerateTree(r.Left, indent + " "); + return str; + } + + /* + * Remove a list of nodes from the tree. + * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree + * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, + leaving the original objects intact (in case something still references them) + */ + public function RemoveNodes(nodes:Array, fullyDestroy = true) + { + + /* DEBUG CHECKS */ + /* + this.PerformDebugCheck(); + + var str = ""; + for (var i = 0; i < nodes.length; i++) + { + str += nodes[i].NodeID + "\n"; + } + + var orig = nodes.concat(); + + var strs = [str, EnumerateTree()]; + + RenderDetailsBox.StartTrack("PackRemoveTime"); + + for (var i = 0; i < nodes.length; i++) + { + var n:RectangleNode = nodes[i]; + if (n.Host != this) + { + throw new Error("bad host!"); + } + } + */ + /* END DEBUG CHECKS */ + + var i, n:RectangleNode, p:RectangleNode; + + // setup the Removed flag on every node that should be removed + // we also check at this time to see if any more nodes need to be removed, such as a parent of + // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + if (n.Host == this) + { + n.Removed = true; + + if (n.InUse) + { + // sum up the total removed area + area -= n.Rect.width * n.Rect.height; + } + + if (n.Parent != null) + { + p = n.Parent; + // check and see if the current node's parent still has any valid children + if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) + { + // all of the current nodes siblings are either being removed or are blank, so + // we can remove the parent too + if (p.Left.IsFreeSpace) + { + // the left child was empty space before, so we can remove it (if it wasn't + // empty space it is already being removed so it doesn't need to be added + // to the list) + if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); + } + if (p.Right.IsFreeSpace) + { + // the right child was empty space before, so we can remove it + if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); + } + if (p != root && nodes.indexOf(p) == -1) + { + // remove the parent node too (provided it isn't the root!) + nodes.push(p); + } + } + } + } + } + + // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, + // so go ahead and remove them + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + + if (n.Parent != null) + { + // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not + // also getting removed!) + p = n.Parent; + + if (!p.Removed) + { + if (p.Left && p.Right) + { + var newNode:RectangleNode; + if (p.Left.Removed && p.Right.Removed) + { + // both children were removed, but the parent wasn't, so the parent must be root + // (since we never remove the root) + if (p != root) + { + throw new Error("should be root"); + } + p.Left.Parent = null; + p.Right.Parent = null; + p.Left = null; + p.Right = null; + p.InUse = false; + } else if (!p.Left.Removed) { + // Right node removed, Left node not removed + if (!p.Left.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Right); + newNode.UpdateLinksFromNode(p.Right); + } + // Left node is used + p.Right.InUse = false; + p.Right.Left = null; + p.Right.Right = null; + p.Right.Removed = false; + } else { + throw new Error("should have been caught above!"); + } + } else { + // Left node removed, Right node not removed + if (!p.Right.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Left); + newNode.UpdateLinksFromNode(p.Left); + } + // Left node is used + //p.Left.Removed = true; + p.Left.InUse = false; + p.Left.Left = null; + p.Left.Right = null; + p.Left.Removed = false; + //p.Left.Parent = null; + } else { + throw new Error("should have been caught above!"); + } + } + } else { + // huh? how does n.Parent == p but p has no children? something went wrong + throw new Error("shouldn't have gotten here"); + } + } + } + //strs.push(EnumerateTree()); + } + } + + public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode + { + + var node:RectangleNode = FindSizedNode(w, h, root); + + if (node == null) + { + //UHOH, texture full + return null; + } + area += w * h; + node.InUse = true; + + var splitVertFirstCost = 0; + if (w < node.Rect.width) + { + splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); + } + + var splitHorizFirstCost = 0; + if (h < node.Rect.height) + { + splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); + } + + + + if (splitVertFirstCost <= splitHorizFirstCost) + { + node.Flags.push("SplitVertFirst"); + if (w < node.Rect.width) + { + node.Flags.push("SplitVert"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + if (h < node.Rect.height) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + } else { + node.Flags.push("SplitHorzFirst"); + if (h < node.Rect.height) + { + node.Flags.push("SplitVert"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + if (w < node.Rect.width) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + } + NextAllocationID++; + if (useInstead) + { + useInstead.MakeFromNode(node); + useInstead.UpdateLinksFromNode(node); + useInstead.Flags = node.Flags; + node = useInstead; + node.Flags.push("UseInstead"); + } + + //if (!CheckOKNode(node)) node.Flags.push("BadNode"); + + return node; + } + public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) + { + if (r == null) r = this.root; + if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) + { + var ancestor:RectangleNode = FindCommonNode(n, r); + throw new Error("bad node allocated!"); + return false; + } + var ok = true; + if (r.Left) ok = ok && CheckOKNode(n, r.Left); + if (r.Right) ok = ok && CheckOKNode(n, r.Right); + return ok; + } + + public function PerformDebugCheck() + { + DebugInternal(this.root); + } + + protected function DebugInternal(n:RectangleNode) + { + if (n.Host != this) + { + throw new Error("problem with host!"); + } + if (n.IsFreeSpace) + { + if (n.Left || n.Right) + { + throw new Error("shouldn't have children"); + } + } + if ((n.Left && !n.Right) || (n.Right && !n.Left)) + { + throw new Error("mismatched children"); + } + if (n.Left && n.Left.Parent != n) + { + throw new Error("left child has bad parent"); + } + if (n.Right && n.Right.Parent != n) + { + throw new Error("right child has bad parent"); + } + if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) + { + throw new Error("problem with parent"); + } + if (n.Left) DebugInternal(n.Left); + if (n.Right) DebugInternal(n.Right); + } + + public function FindCommonNode(a:RectangleNode, b:RectangleNode) + { + var aHistory = []; + var bHistory = []; + while (a != null) + { + aHistory.push(a); + a = a.Parent; + } + while (b != null) + { + bHistory.push(b); + b = b.Parent; + } + var i = aHistory.length - 1; + var j = bHistory.length - 1; + var same = null; + while (i >= 0 && j >= 0) + { + if (aHistory[i] == bHistory[j]) + { + same = aHistory[i]; + } else { + break; + } + i--; + j--; + } + return same; + } + + public function TestRender() + { + while (testRender.numChildren > 0) + { + testRender.removeChildAt(0); + } + testRender.graphics.clear(); + TestRenderNode(root, testRender); + return testRender; + } + protected function TestRenderNode(n:RectangleNode, m:MovieClip) + { + var g:MovieClip = new MovieClip(); + m.addChild(g); + g.graphics.lineStyle(1, 0, 1); + if (n.Left != null) TestRenderNode(n.Left, m); + if (n.Left != null) TestRenderNode(n.Right, m); + if (n.InUse) + { + g.graphics.beginFill(0xFFFF00, 0.2); + } + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + if (n.InUse) + { + g.graphics.endFill(); + var t:TextField = new TextField(); + t.text = n.NodeID; + t.x = n.Rect.x + n.Rect.width / 2.0; + t.y = n.Rect.y + n.Rect.height / 2.0; + g.addChild(t); + g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); + g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); + } + + } + public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) + { + if (n.InUse) + { + //_trace(Math.round(n.LastAccessTime / 1000)); + } + var p:RectangleNode = n.Parent; + if (p) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); + g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); + g.graphics.endFill(); + t.text = p.NodeID; + if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); + g.oldListener = function(e){MouseOver(p, g, t);}; + g.addEventListener(MouseEvent.CLICK, g.oldListener); + } + } + public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(0xFFFF00, 0.2); + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + g.graphics.endFill(); + t.text = n.NodeID; + } + protected function SplitVert(node:RectangleNode, leftWidth) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function SplitHoriz(node:RectangleNode, topHeight) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode + { + if (node.InUse) return null; + if (node.Rect.width >= w && node.Rect.height >= h) + { + if (node.Left != null && node.Right != null) + { + var t:RectangleNode = FindSizedNode(w, h, node.Left); + if (t != null) return t; + t = FindSizedNode(w, h, node.Right); + return t; + } else { + return node; + } + } + return null; + } + + public function LoadTree(details) + { + this.root = new RectangleNode(0, 0, 0, 0, this); + root.ReadJSON(details); + + this.NextAllocationID = 0; + this.area = 0; + + var queue:Array = new Array(); + queue.push(root); + while (queue.length > 0) + { + var node:RectangleNode = queue.shift(); + node.AllocationID = NextAllocationID; + node.MinAllocationID = NextAllocationID; + if (node.Left) queue.push(node.Left); + if (node.Right) queue.push(node.Right); + if (node.InUse) this.area += node.Rect.width * node.Rect.height; + } + NextAllocationID++; + } + + public function GetNodePath(node:RectangleNode) + { + var output:String = ""; + while (node != this.root) + { + output = (node == node.Parent.Left ? "l" : "r") + output; + node = node.Parent; + } + return output; + } + + public function GetNodeFromPath(path:String):RectangleNode + { + var node:RectangleNode = this.root; + for (var i = 0; i < path.length; i++) + { + if (!node) return null; + if (path.charAt(i) == "r") + { + node = node.Right; + } else { + node = node.Left; + } + } + return node; + } + } +} diff --git a/flash/util/Utils.as b/flash/util/Utils.as new file mode 100644 index 0000000..f792003 --- /dev/null +++ b/flash/util/Utils.as @@ -0,0 +1,389 @@ +package util +{ + import flash.display.*; + import flash.geom.*; + public class Utils + { + public static function GetChildren(clip:MovieClip):Array + { + var ret:Array = []; + for (var i = 0; i < clip.numChildren; i++) + { + ret.push(clip.getChildAt(i)); + } + return ret; + } + + /* + * angle difference + * (range -Math.PI to Math.PI) + */ + public static function GetAngleDiff(a, b) + { + var angleDiff = b - a; + + while (angleDiff > Math.PI) + { + angleDiff -= Math.PI * 2; + } + while (angleDiff < -Math.PI) + { + angleDiff += Math.PI * 2; + } + return angleDiff; + } + + /* + * angle difference + * (range 0 to Math.PI) + */ + public static function GetAngleDiffAbs(a, b) + { + var angleDiff = GetAngleDiff(a, b); + while (angleDiff < 0) + { + angleDiff += Math.PI * 2; + } + + if (angleDiff > Math.PI) + { + angleDiff = Math.PI * 2 - angleDiff; + } + + return angleDiff; + } + + public static function GetTransform(from:Matrix, to:Matrix) + { + var i:Matrix = from.clone(); + i.invert(); + var m:Matrix = to.clone(); + m.concat(i); + return m; + } + + public static function Decompose(m:Matrix) + { + var s:Point = ScaleFromMat(m); + m = m.clone(); + + var sxUnit = s.x >= 0 ? 1 : -1; + var syUnit = s.y >= 0 ? 1 : -1; + + m.scale(sxUnit, syUnit); + + //m.a /= sxUnit; + //m.d /= syUnit; + var rot = RotFromMat(m); + return {sx:s.x, sy:s.y, rot:rot}; + } + + public static function RotFromMat(m:Matrix) + { + return Math.atan2(-m.c, m.a); + } + + public static function ScaleFromMat(m:Matrix):Point + { + var xAxisX = m.a; + var xAxisY = m.c; + + var yAxisX = m.b; + var yAxisY = m.d; + + var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); + if (m.a < 0) sx *= -1; + + var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); + if (m.d < 0) sy *= -1; + + return new Point(sx, sy); + } + + public static function TransformRect(r:Rectangle, m:Matrix) + { + var p1:Point = new Point(r.left, r.top); + var p2:Point = new Point(r.right, r.top); + var p3:Point = new Point(r.left, r.bottom); + var p4:Point = new Point(r.right, r.bottom); + + p1 = m.transformPoint(p1); + p2 = m.transformPoint(p2); + p3 = m.transformPoint(p3); + p4 = m.transformPoint(p4); + + r.left = Math.min(p1.x, p2.x, p3.x, p4.x); + r.top = Math.min(p1.y, p2.y, p3.y, p4.y); + r.right = Math.max(p1.x, p2.x, p3.x, p4.x); + r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); + } + + public static function RoundRect(r:Rectangle) + { + r.left = Math.floor(r.left); + r.top = Math.floor(r.top); + r.right = Math.ceil(r.right); + r.bottom = Math.ceil(r.bottom); + } + + public static function ScaleRect(r:Rectangle, s) + { + r.left *= s; + r.top *= s; + r.right *= s; + r.bottom *= s; + } + + public static function RecursivelyStop(clip) + { + if (clip is MovieClip) + { + clip.stop(); + } + if (clip is DisplayObjectContainer) + { + for (var i = 0; i < clip.numChildren; i++) + { + RecursivelyStop(clip.getChildAt(i)); + } + } + } + + public static function WeirdGotoFrame(clip:MovieClip, frame) + { + var dir = clip.currentFrame > frame ? -1 : 1; + while (clip.currentFrame != frame) + { + RecurseDir(clip, dir); + } + } + + protected static function RecurseDir(clip:MovieClip, dir) + { + for (var i = 0; i < clip.numChildren; i++) + { + var child = clip.getChildAt(i); + if (child is MovieClip) + { + RecurseDir(child, dir); + } + } + if (dir == 1) + { + clip.nextFrame(); + } else { + clip.prevFrame(); + } + } + + protected static var tempSpace:BitmapData = null; + protected static var tempSpaceRect:Rectangle = new Rectangle(); + protected static var tempSpaceMatrix:Matrix = new Matrix(); + protected static var tempSpaceZero:Point = new Point(); + protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); + protected static var lastDrawOffset:Point = new Point(); + public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle + { + if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); + + var oldPad = 0; + var padAmount = 5; + + var ret:Rectangle = new Rectangle(); + + var baseBounds:Rectangle = clip.getBounds(clip); + + var boundsClip:DisplayObject = null; + if (clip is DisplayObjectContainer) + { + boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); + } + + if (boundsClip != null) + { + baseBounds = boundsClip.getBounds(clip); + } + + if (useMatrix) + { + TransformAABBRect(baseBounds, useMatrix); + } + + if (boundsClip != null) + { + return baseBounds; + } + + var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); + var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); + if (tempSpace == null) + { + tempSpace = new BitmapData(minW, minH, true, 0x0); + } + if (tempSpace.width < minW || tempSpace.height < minH) + { + tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); + } + + var r:Rectangle = new Rectangle(); + + baseBounds.left = Math.floor(baseBounds.left); + baseBounds.right = Math.ceil(baseBounds.right); + + baseBounds.top = Math.floor(baseBounds.top); + baseBounds.bottom = Math.ceil(baseBounds.bottom); + + var i; + + var needsChecking = true; + while (needsChecking) + { + needsChecking = false; + r.left = baseBounds.left - padAmount; + r.right = baseBounds.right + padAmount; + + r.top = baseBounds.top - padAmount; + r.bottom = baseBounds.bottom + padAmount; + + ret = r.clone(); + + tempSpaceRect.x = tempSpaceRect.y = 0; + tempSpaceRect.width = tempSpace.width; + tempSpaceRect.height = tempSpace.height; + tempSpace.fillRect(tempSpaceRect, 0x0); + + tempSpaceMatrix.identity(); + if (useMatrix) + { + tempSpaceMatrix.a = useMatrix.a; + tempSpaceMatrix.b = useMatrix.b; + tempSpaceMatrix.c = useMatrix.c; + tempSpaceMatrix.d = useMatrix.d; + tempSpaceMatrix.tx = useMatrix.tx; + tempSpaceMatrix.ty = useMatrix.ty; + } + tempSpaceMatrix.translate(-r.left, -r.top); + + lastDrawOffset.x = -r.left; + lastDrawOffset.y = -r.top; + tempSpace.draw(clip, tempSpaceMatrix); + + tempSpaceRect.width = 1; + tempSpaceRect.height = r.height; + + var sideMovedIn = 0; + for (i = 0; i < r.width; i++) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.left++; + sideMovedIn++; + } + } + if (ret.left < baseBounds.left - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.width - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.right--; + } + } + if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + sideMovedIn = 0; + tempSpaceRect.width = r.width; + tempSpaceRect.height = 1; + tempSpaceRect.x = 0; + for (i = 0; i < r.height; i++) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.top++; + sideMovedIn++; + } + } + if (ret.top < baseBounds.top - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.height - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.bottom--; + } + } + if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + } + return ret; + } + + public static function TransformAABBRect(r:Rectangle, m:Matrix) + { + var o1X = r.left; + var o1Y = r.top; + + var o2X = r.right; + var o2Y = r.top; + + var o3X = r.left; + var o3Y = r.bottom; + + var o4X = r.right; + var o4Y = r.bottom; + + var n1X = o1X * m.a + o1Y * m.c + m.tx; + var n1Y = o1X * m.b + o1Y * m.d + m.ty; + + var n2X = o2X * m.a + o2Y * m.c + m.tx; + var n2Y = o2X * m.b + o2Y * m.d + m.ty; + + var n3X = o3X * m.a + o3Y * m.c + m.tx; + var n3Y = o3X * m.b + o3Y * m.d + m.ty; + + var n4X = o4X * m.a + o4Y * m.c + m.tx; + var n4Y = o4X * m.b + o4Y * m.d + m.ty; + + r.left = Math.min(n1X, n2X, n3X, n4X); + r.right = Math.max(n1X, n2X, n3X, n4X); + + r.top = Math.min(n1Y, n2Y, n3Y, n4Y); + r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); + } + } +} diff --git a/job.py b/job.py index 989c991..77c09e8 100644 --- a/job.py +++ b/job.py @@ -3,6 +3,7 @@ import json from validate import * from args import * +import copy asset_src_schema = { "type":"object", @@ -69,19 +70,24 @@ base_path = os.path.join(self.out_dir, self.rel_path) if not os.path.exists(base_path): os.makedirs(base_path) + resource_names = [] for i,r in enumerate(resources): - path = os.path.join(base_path, "%s_%04d.png" % (self.name, i)) + resource_name = "%s_%04d.png" % (self.name, i) if len(resources) > 1 else self.name + ".png" + resource_names.append(resource_name) + path = os.path.join(base_path, resource_name) with open(path, "wb") as f: f.write(base64.b64decode(r)) if len(data) == 1: graphic_and_asset = {} (name, graphic_data) = data.items()[0] - graphic_and_asset = {"data":graphic_data} + graphic_and_asset = {"data":graphic_data, "resources":resource_names} with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps(graphic_and_asset)) else: + write_data = copy.deepcopy(data) + write_data["resources"] = resource_names with open(os.path.join(base_path, self.name + ".asset"), "w") as f: - f.write(pretty_dumps(data)) + f.write(pretty_dumps(write_data)) for name,details in data.iteritems(): with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps({"data":self.name + ".asset"})) diff --git a/old/Checkbox.as b/old/Checkbox.as deleted file mode 100644 index c5aaba2..0000000 --- a/old/Checkbox.as +++ /dev/null @@ -1,42 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - - public class Checkbox extends MovieClip - { - public var Enabled:Boolean = true; - public function Checkbox() - { - checkbox.gotoAndStop(1); - checkbox.addEventListener(MouseEvent.CLICK, Clicked); - } - - protected function Clicked(event) - { - if (!Enabled) return; - Toggle(); - if (OnClick != null) OnClick(OnClickParam); - } - - protected var checked = false; - public function set Checked(value) { checked = value; checkbox.gotoAndStop(checked ? 2 : 1); } - public function get Checked() { return checked; } - - public function set Text(value) { text.text = value; } - - public var OnClickParam; - public var OnClick; - - - public function Toggle() - { - checked = !checked; - checkbox.gotoAndStop(checked ? 2 : 1); - - - } - - } - -} diff --git a/old/GraphicExport-app.xml b/old/GraphicExport-app.xml deleted file mode 100644 index 5144634..0000000 --- a/old/GraphicExport-app.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - GraphicExport - 1.0 - GraphicExport - - GraphicExport - - - GraphicExport.swf - standard - false - true - false - portrait - auto - true - true - true - - - false - false - desktop extendedDesktop diff --git a/old/GraphicExport.exe b/old/GraphicExport.exe deleted file mode 100644 index 56315aa..0000000 --- a/old/GraphicExport.exe +++ /dev/null Binary files differ diff --git a/old/GraphicExport.fla b/old/GraphicExport.fla deleted file mode 100644 index 0b78ed7..0000000 --- a/old/GraphicExport.fla +++ /dev/null Binary files differ diff --git a/old/GraphicExport.swf b/old/GraphicExport.swf deleted file mode 100644 index 542db97..0000000 --- a/old/GraphicExport.swf +++ /dev/null Binary files differ diff --git a/old/NewGraphicDialog.as b/old/NewGraphicDialog.as deleted file mode 100644 index 152011c..0000000 --- a/old/NewGraphicDialog.as +++ /dev/null @@ -1,224 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - import flash.events.*; - import flash.filesystem.File; - import flash.net.FileFilter; - import Defs.GraphicDef; - import flash.text.engine.GraphicElement; - - public class NewGraphicDialog extends MovieClip - { - - public function NewGraphicDialog() - { - // constructor code - Init(); - } - - var typeButtons:Array = new Array(); - - public function Init() - { - graphicPath.text = "Path to Graphic Here"; - - this.removeChild(browseButton); - - var newBrowseButton = new UI_GenericBlueButton(); - newBrowseButton.Text = "Browse"; - newBrowseButton.OnClick = BrowseForFile; - newBrowseButton.x = browseButton.x + (newBrowseButton.width / 2); - newBrowseButton.y = browseButton.y + (newBrowseButton.height / 2); - addChild(newBrowseButton); - - var newTestButton = new UI_GenericBlueButton(); - newTestButton.Text = "Export"; - newTestButton.OnClick = TestFile; - newTestButton.x = testButton.x + (newTestButton.width / 2); - newTestButton.y = testButton.y + (newTestButton.height / 2); - addChild(newTestButton); - - this.removeChild(typePlaceholderButton); - - var typeX = typePlaceholderButton.x; - var typeY = typePlaceholderButton.y + (typePlaceholderButton.height / 2); - - - var typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Graphic (1)"; - typeButton.OnClick = function(){ SetType(1); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Skeletal (3)"; - typeButton.OnClick = function(){ SetType(3); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Scene (6)"; - typeButton.OnClick = function(){ SetType(6); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - animationCheckbox.Checked = true; - //browseButton - //typePlaceholderButton - //usesInput - //usesText.text = "" - } - - var usesInputDefaultText = "Comma Seperated List of Uses Here"; - - public static var fakeID = 9999999; - public function TestFile() - { - fakeID++; - var graphicName = graphicPath.text; - var graphicData = {id:fakeID,graphic:graphicPath.text,v:1,fs:0,p:0,type:selectedType}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new GraphicDef(graphicData); - - this.Hide(); - graphicExport.ExportItem(graphicDef); - } - - var selectedType = 1; - public function SetType(type:Number) - { - selectedType = type; - - for(var i = 0; i < typeButtons.length; i++) - { - typeButtons[i].Enabled = true; - } - - animationCheckbox.visible = false; - - switch(type) - { - case 1: { - typeButtons[0].Enabled = false; - animationCheckbox.visible = true; - break; - } - case 3: typeButtons[1].Enabled = false; break; - case 6: typeButtons[2].Enabled = false; break; - } - } - - var graphicExport:GraphicExport; - public function Show(parentClip) - { - this.graphicExport = parentClip; - - parentClip.addChild(this); - - SetType(selectedType); - - var graphicList = GameData.Instance().GraphicDefines; - - var usesString:String = ""; - var uniqueUseTypes:Array = new Array(); - for (var i = 0; i < graphicList.length; i++) - { - var graphicDef:GraphicDef = graphicList[i]; - var uses = graphicDef.ExportParams['uses']; - for (var usage in uses) - { - if (uniqueUseTypes[uses[usage]] == null) - { - uniqueUseTypes[uses[usage]] = uses[usage]; - usesString += uses[usage] + ", "; - } - } - } - - graphicPath.text = ""; - - } - - public function CloseClicked(event) - { - Hide(); - } - - public function Hide() - { - if (this.parent != null) this.parent.removeChild(this); - } - - public function BrowseForFile() - { - var file:File = new File(); - var swfTypeFilter:FileFilter = new FileFilter("SWF Files","*.swf"); - file.addEventListener(Event.SELECT, openFile); - file.browse([swfTypeFilter]); - } - - private function openFile(event:Event):void - { - _strace(event.target.nativePath); - var path:String = event.target.nativePath; - var pathParts:Array = path.split("Graphics\\"); - if (pathParts.length == 2) - { - var fileRemainder:String = pathParts[1]; - var withoutExtension:String = fileRemainder.split(".")[0]; - var pattern:RegExp = /\\/g; - withoutExtension = withoutExtension.replace(pattern, "/"); - _strace(withoutExtension); - graphicPath.text = withoutExtension; - - if (withoutExtension.indexOf("Backgrounds") > -1) - { - SetType(6); - } - - if (withoutExtension.indexOf("Monsters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Characters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Portraits") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Quest") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Equipment") > -1) - { - SetType(1); - } - - - } - } - - - } - -} diff --git a/old/PNGExportHelper.as b/old/PNGExportHelper.as deleted file mode 100644 index f8c4c9d..0000000 --- a/old/PNGExportHelper.as +++ /dev/null @@ -1,253 +0,0 @@ -package -{ - import flash.display.*; - import com.adobe.images.*; - import flash.utils.*; - import flash.net.*; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import flash.geom.Point; - - public class PNGExportHelper - { - public static var UseExpandedBitmaps = false; - public static var AlphaThreshold = 5; - - private static function ExpandBitmapBorders(bd:BitmapData, bgColor = 0x0, passes = 1):BitmapData - { - /* - var thresh:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - thresh.threshold(bd, bd.rect, new Point(), "<", (20 << 24), bgColor, 0xFF000000, true); - */ - var sampled:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - bd.lock(); - sampled.lock(); - - for (var y = 0; y < bd.height; y++) - { - for (var x = 0; x < bd.width; x++) - { - var oldVal:uint = bd.getPixel32(x, y); - var a:uint = (oldVal & 0xFF000000) >>> 24; - var rgb:uint = (oldVal & 0xFFFFFF); - if (a > AlphaThreshold) - { - sampled.setPixel32(x, y, (0xFF << 24) | rgb); - } - else - { - sampled.setPixel32(x, y, bgColor); - } - } - } - sampled.unlock(); - bd.unlock(); - - return ExpandBitmapBordersInternal(sampled, bgColor, passes); - } - - private static function ExpandBitmapBordersInternal(bd:BitmapData, bgColor, passes):BitmapData - { - var output:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - - var scale = 16; - var scaled:BitmapData = new BitmapData(bd.width/scale, bd.height/scale, true, bgColor); - var mat:Matrix = new Matrix(); - mat.scale(1/scale, 1/scale); - scaled.draw(bd, mat, null, null, null, true); - - output.lock(); - - var colors:Array = new Array(); - var weights:Array = new Array(); - - for (var oy = 0; oy < scaled.height; oy++) - { - - for (var ox = 0; ox < scaled.width; ox++) - { - - var scaledVal:uint = scaled.getPixel32(ox, oy); - var scaleda:uint = (scaledVal & 0xFF000000) >>> 24; - if (scaleda == 0 || scaleda == 255) - { - output.copyPixels(bd, new Rectangle(ox * scale, oy * scale, scale, scale), new Point(ox * scale, oy * scale)); - continue; - } else { - //_strace(scaleda+""); - } - - - for (var y = oy * scale; y < oy * scale + scale; y++) - { - for (var x = ox * scale; x < ox * scale + scale; x++) - { - var oldVal:uint = bd.getPixel32(x, y); - var a:uint = (oldVal & 0xFF000000) >>> 24; - var rgb:uint = (oldVal & 0xFFFFFF); - - if (a == 0 && rgb == bgColor) - { - colors.length = 0; - weights.length = 0; - - for (var y1 = y - 2; y1 <= y + 2; y1++) - { - for (var x1 = x - 2; x1 <= x + 2; x1++) - { - var dist = Math.abs(x1 - x) + Math.abs(y1 - y); - if (dist >= 3) continue; - - if (x1 >= 0 && x1 < bd.width && y1 >= 0 && y1 < bd.height) - { - colors.push(bd.getPixel(x1, y1)); - weights.push(1 - dist * 0.2); - } - } - } - - var newVal = AveragePixels(colors, weights, bgColor); - if (newVal == null) - { - newVal = oldVal; - } - else - { - var newR:uint = (newVal & 0xFF0000) >> 16; - var newG:uint = (newVal & 0xFF00) >> 8; - var newB:uint = (newVal & 0xFF); - - if (newVal != 0 && colors.length >= 4) - { - var bp = true; - } - - var sorted = colors.sort(function(a, b) - { - var aR:uint = (a & 0xFF0000) >> 16; - var aG:uint = (a & 0xFF00) >> 8; - var aB:uint = (a & 0xFF); - - var bR:uint = (b & 0xFF0000) >> 16; - var bG:uint = (b & 0xFF00) >> 8; - var bB:uint = (b & 0xFF); - - var diffA = Math.abs(aR - newR) + Math.abs(aG - newG) + Math.abs(aB - newB); - var diffB = Math.abs(bR - newR) + Math.abs(bG - newG) + Math.abs(bB - newB); - - return diffA - diffB; - - }, Array.RETURNINDEXEDARRAY | Array.DESCENDING); - - var toRemove = Math.min(2, colors.length - 4); - var removed = 0; - for (var i = 0; i < colors.length; i++) - { - var index = sorted.indexOf(i + removed); - if (index < toRemove) - { - colors.splice(i, 1); - weights.splice(i, 1); - removed++; - i--; - if (removed == toRemove) break; - } - } - - var fixOutliersVal = AveragePixels(colors, weights, bgColor); - if (fixOutliersVal == null) newVal = (0xFF << 24) | newVal; - - newVal = (0xFF << 24) | fixOutliersVal; - } - - output.setPixel32(x, y, newVal); - } - else - { - output.setPixel32(x, y, oldVal); - } - } - } - }//end outer scaled x - }//End outer scaled y - - bd.unlock(); - output.unlock(); - - passes--; - if (passes > 0) - { - return ExpandBitmapBordersInternal(output, bgColor, passes); - } - else - { - return output; - } - } - - private static function AveragePixels(colors:Array, weights:Array, bgColor:uint):uint - { - var rTotal = 0; - var gTotal = 0; - var bTotal = 0; - - var wTotal = 0; - - for (var i = 0; i < colors.length; i++) - { - var color:uint = colors[i]; - var a:uint = (color & 0xFF000000) >>> 24; - var rgb:uint = (color & 0xFFFFFF); - - if (a == 0 && rgb == bgColor) - { - colors.splice(i, 1); - weights.splice(i, 1); - i--; - continue; - } - - var r:uint = (rgb & 0xFF0000) >>> 16; - var g:uint = (rgb & 0xFF00) >>> 8; - var b:uint = (rgb & 0xFF); - var w = weights[i]; - - rTotal += w * r; - gTotal += w * g; - bTotal += w * b; - - wTotal += w; - } - - if (wTotal == 0) - { - return null; - } - - rTotal /= wTotal; - gTotal /= wTotal; - bTotal /= wTotal; - - var rFinal = Math.max(0, Math.min(255, Math.round(rTotal))); - var gFinal = Math.max(0, Math.min(255, Math.round(gTotal))); - var bFinal = Math.max(0, Math.min(255, Math.round(bTotal))); - - return (uint(rFinal) << 16) | (uint(gFinal) << 8) | (uint(bFinal)); - } - - - - public static function GetExportPNG(bd:BitmapData):ByteArray - { - if (!UseExpandedBitmaps) return PNGEncoder.encode(bd); - - var expanded:BitmapData = ExpandBitmapBorders(bd, 0x0, 2); - - //var fr:FileReference = new FileReference(); - //fr.save(PNGEncoder.encode(expanded), "output.png"); - - return PNGEncoderWithAlpha.encode(expanded, bd); - } - - } -} \ No newline at end of file diff --git a/old/PreviewHolder.as b/old/PreviewHolder.as deleted file mode 100644 index 587bf68..0000000 --- a/old/PreviewHolder.as +++ /dev/null @@ -1,57 +0,0 @@ -package { - import flash.display.MovieClip; - - public class PreviewHolder extends MovieClip - { - - var startingWidth = 1024; - var startingHeight = 1024; - - public function PreviewHolder() - { - startingWidth = this.width; - startingHeight = this.height; - } - - var clips:Array = new Array(); - public function AddClip(clip) - { - clips.push(clip); - this.addChild(clip); - ArrangeClips(); - } - - public function ArrangeClips() - { - var numCols = Math.ceil(Math.sqrt(clips.length)); - var maxY = 0; - var maxX = 0; - var clipIndex = 0; - for (var row = 0; row < numCols; row++) - { - var clipX = 0; - var clipY = maxY; - for (var col = 0; col < numCols; col++) - { - if (clipIndex == clips.length) break; - clips[clipIndex].x = clipX; - clips[clipIndex].y = clipY; - clipX += clips[clipIndex].width; - var clipBottom = clips[clipIndex].y + clips[clipIndex].height; - if (clipBottom > maxY) maxY = clipBottom; - - var clipRight = clips[clipIndex].x + clips[clipIndex].width; - if (clipRight > maxX) maxX = clipRight; - clipIndex++; - } - } - - var scale = Math.min(startingWidth / maxX, startingHeight / maxY); - if (scale > 1) scale = 1; - - this.scaleX = this.scaleY = scale; - } - - } - -} diff --git a/old/Utils.as b/old/Utils.as deleted file mode 100755 index 02b4f12..0000000 --- a/old/Utils.as +++ /dev/null @@ -1,1202 +0,0 @@ -package old -{ - /* This class has functions similar to the Utils.as in the /flash/Dialogs folder. However, some of - * those functions are different here than in /flash/Dialogs/Utils.as for... reasons? flash folder reasons! - */ - import flash.utils.*; - import flash.net.*; - import flash.display.*; - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.geom.Point; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import flash.geom.ColorTransform; - import fl.motion.Color; - import fl.transitions.Tween; - import fl.transitions.easing.*; - import fl.transitions.TweenEvent; - import flash.net.navigateToURL; - import flash.external.ExternalInterface; - import flash.system.Capabilities; - import flash.filters.*; - import flash.filters.ColorMatrixFilter; - import com.adobe.images.JPGEncoder; - import flash.globalization.DateTimeFormatter; - - import djarts.utils.Base64; - import djarts.utils.PNGEnc; - import User.UserOptions; - - public class Utils - { - //["K","M","B","T","q", "Q", "s", "S","O","N","d","U","D","!","@","#","$","%","^","&","*"] - static var symbols = ["K","M","B","t","q", "Q", "s", "S","o","n","d","U","D","T","Qt","Qd","Sd","St","O","N","v","c"]; - static var divisors = []; - - public static function FormatBigNumber(number:*, round:Boolean=false):String - { - if (number < 0) return '-' + FormatBigNumber(Math.abs(number), round); - - var isWholeNumber = (Math.floor(number) == number); - round = round || isWholeNumber; - - if (number < 1000) - { - if (round) - { - return Math.round(number).toString(); - } - else - { - var decimalPlaces = (number >= 100) ? 1 : 2; // Below 100, show two decimal places. Above, only one. - var roundMult = Math.pow(10, decimalPlaces); - var rounded = Math.round(number); - var bigRounded = Math.round(number * roundMult); - var roundedDifferenceProportion = Math.abs(bigRounded / roundMult - rounded) / rounded; - - if (roundedDifferenceProportion < 0.001) - { - // Not a whole number, but the decimal places aren't worth showing - // Below also handles this, but is slower - return rounded.toString(); - } - else - { - var str:String = bigRounded.toString(); - str = str.substr(0, str.length - decimalPlaces) + "." + str.substr(str.length - decimalPlaces); - - while (str.charAt(str.length - 1) == "0") str = str.substr(0, str.length - 1); //should only ever happen once - if (str.charAt(str.length - 1) == ".") str = str.substr(0, str.length - 1); //probably won't happen at all - - return str; - } - } - } - - // Determine which symbol to use - var power = Math.floor(Math.log(number) / Math.log(1000)); - var index = Math.min(power-1, symbols.length-1); - var amount = number / Math.pow(1000, index+1); - var symbol = (index >= 0 && index < symbols.length) ? symbols[index] : ""; - - // If it's too big for a symbol (or if we just WANT to) - if (amount >= 1000 || UserOptions.ForceScientific) - { - // scientific notation - var power = Math.floor(Math.log(number) / Math.log(10)); - var num = number / Math.pow(10, power); - if (num == 10) { - num = 1; - power += 1; - } - var numString = "" + num; - numString = numString.substr(0, Math.min(4, numString.length)); - return numString + "e" + power; - - } - else - { - // Format with the symbol - // determine number of whole digits (will dictate how many decimals we show) - var whole = Math.floor(amount); - var amount_str:String = String(whole); - - var decimalDivider = 100/Math.pow(10,amount_str.length-1); - - //round to nearest decimal place - amount = int(amount*decimalDivider)/decimalDivider; - - var amountString:String = amount.toString(); - - var noDecimal:String = amountString.replace(".",""); - if (noDecimal.length == 2) - { - if (amountString.indexOf(".") != -1) amountString += "0"; - else amountString += ".0"; - } - else if (noDecimal.length == 1) amountString += ".00"; - - return amountString+symbol; // concat symbol - } - } - - private static var BigNumberRegex = new RegExp(/(\d*),?(\d*)(.*)/); - // Note-DG: This is mostly just used for definitions in the database, that don't require precision. - // This way we can define values in the database as 100B instead of 100000000000. - public static function ParseBigNumberString(number:String):Number - { - var regexArray:Array = BigNumberRegex.exec(number); - var magnitude = symbols.indexOf(regexArray[3]); - var thousands:Number; - if (regexArray[1]) { - thousands = regexArray[1]; - if (regexArray[2]) { // if numbers are split by comma, multiply by 1000 - thousands *= 1000; - } - } else { - thousands = 0; - } - var hundreds:Number = regexArray[2] ? regexArray[2] : 0; - - return (thousands + hundreds) * Math.pow(1000, magnitude + 1); - } - - public static function ParseNumberRange(range:String):Array - { - var split:Array = range.split(','); - return [Number(split[0]), Number(split[1])]; - } - - public static function DesaturateFilter() - { - var desatMatrix:Array = []; - var cmFilter; - - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // red - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // green - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // blue - desatMatrix = desatMatrix.concat([0, 0, 0, 1, 0]); // alpha - cmFilter = new ColorMatrixFilter(desatMatrix); - - return cmFilter; - } - - public static function GetUserAgent():String - { - try - { - var userAgent = ExternalInterface.call("window.navigator.userAgent.toString"); - var browser:String = "[Unknown Browser]"; - - if (userAgent.indexOf("Safari") != -1) - { - browser = "Safari"; - } - if (userAgent.indexOf("Firefox") != -1) - { - browser = "Firefox"; - } - if (userAgent.indexOf("Chrome") != -1) - { - browser = "Chrome"; - } - if (userAgent.indexOf("MSIE") != -1) - { - browser = "Internet Explorer"; - } - if (userAgent.indexOf("Opera") != -1) - { - browser = "Opera"; - } - } - catch (e:Error) - { - //could not access ExternalInterface in containing page - return "[No ExternalInterface]"; - } - - return browser; - } - - public static function GetScreenshot(stage:Stage):String { - var scale:Number = 0.25; - var result:String = null; - var blurFilter:BlurFilter = new BlurFilter(3, 3, BitmapFilterQuality.HIGH); - - var bData:BitmapData = new BitmapData(stage.stageWidth * scale, - stage.stageHeight * scale, false, 0x348400); - var matrix:Matrix = new Matrix(); - matrix.scale(scale, scale); - - bData.draw(stage, matrix); - bData.applyFilter(bData, bData.rect, new Point(0, 0), blurFilter); - - - var imgBytes:ByteArray = new JPGEncoder(80).encode(bData); - //var imgBytes:ByteArray = PNGEnc.encode(bData); - if (imgBytes) { - var screenshotBase64:String = Base64.encode(imgBytes); - if (screenshotBase64) { - result = screenshotBase64; - } - } - - return result; - } - - public static function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function PlayerVersion() - { - - // Get the player's version by using the getVersion() global function. - var versionNumber:String = Capabilities.version; - - // The version number is a list of items divided by "," - var versionArray:Array = versionNumber.split(","); - var length:Number = versionArray.length; - //for(var i:Number = 0; i < length; i++) _strace("versionArray["+i+"]: "+versionArray[i]); - - // The main version contains the OS type too so we split it in two - // and we'll have the OS type and the major version number separately. - var platformAndVersion:Array = versionArray[0].split(" "); - //for(var j:Number = 0; j < 2; j++) _strace("platformAndVersion["+j+"]: "+platformAndVersion[j]); - //_strace("-----"); - - var majorVersion:Number = parseInt(platformAndVersion[1]); - var minorVersion:Number = parseInt(versionArray[1]); - var buildNumber:Number = parseInt(versionArray[2]); - - return Number(majorVersion+"."+minorVersion); - } - - - public static function OpenLocalURLTop(url) - { - navigateToURL(new URLRequest(GameSettings.Approot+url), "_top" ); - } - - public static function OpenLocalURL(url) - { - navigateToURL(new URLRequest(GameSettings.Approot+url), "_blank" ); - } - - public static function OpenURL(url, window = "_blank") - { - navigateToURL(new URLRequest(url), window); - } - - public static var ExitFullScreenCallback; - - public static function WallPublish(title:String, desc1:String, desc2:String, image:String, url = null, action = null) - { - if (Utils.ExitFullScreenCallback) Utils.ExitFullScreenCallback(); - //_strace(title + "\n" + desc1 + "\n" + desc2 + "\n" + image + "\n"); - ExternalInterface.call("askToPublish", title, url, desc1, desc2, image, action); - - //if (Settings.Platform == Settings.HI5) { - //DialogManager.Instance().ShowMessageBox("The message was posted to your wall!", "", "OK", null); - //} - } - - public static function SendToRecipients(recipients:Array, description, data) - { - if (!GameSettings.IsFacebook) return; - - if (Utils.ExitFullScreenCallback) Utils.ExitFullScreenCallback(); - try { - ExternalInterface.call("sendToRecipients", recipients, description ,data); - } - catch (e) - { - _strace(e.message); - } - } - - - public static function GetFriendData() - { - try { - return ExternalInterface.call("pollInviteData"); - } - catch (e) - { - _strace(e.message); - } - } - - - public static function singleBounceEase(t:Number, b:Number, c:Number, d:Number):Number - { - t = t / d; - if (t < 0.7) { - t *= 1.0 / 0.65; - return c * (t * t) + b; - } - return c * (t * t) + b; - } - - public static function Finish(e:TweenEvent) - { - //_strace("done " + e.currentTarget.obj.x + " " + e.currentTarget.obj.y + " " + e.currentTarget.obj.scaleX + " " + e.currentTarget.obj.scaleY); - e.currentTarget.removeEventListener(TweenEvent.MOTION_FINISH, Finish); - } - public static function Popup(mc, startScale = 0.8, finishCallback = null) - { - var rect:Rectangle = mc.getRect(mc); - var targetX = mc.x; - var targetY = mc.y; - var centerX = mc.x + rect.left + mc.width / 2.0; - var centerY = mc.y + rect.top + mc.height / 2.0; - var startX = centerX - (rect.left + mc.width / 2.0) * startScale; - var startY = centerY - (rect.top + mc.height / 2.0) * startScale; - var tweenSX = new Tween(mc, "scaleX", singleBounceEase, startScale, 1.0, 4, false); - if (finishCallback) tweenSX.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenSY = new Tween(mc, "scaleY", singleBounceEase, startScale, 1.0, 4, false); - if (finishCallback) tweenSY.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenX = new Tween(mc, "x", singleBounceEase, startX, targetX, 4, false); - if (finishCallback) tweenX.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenY = new Tween(mc, "y", singleBounceEase, startY, targetY, 4, false); - if (finishCallback) tweenY.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - return [tweenSX, tweenSY, tweenX, tweenY]; - } - public static function StringSplit(s:String, delim:String, max:int = -1):Array - { - var ret:Array = s.split(delim); - if (max != -1) { - var more:String = ret.slice(max - 1).join(delim); - ret.splice(max - 1); - ret[max - 1] = more; - } - return ret; - } - - public static function StringStartsWith(str:String, substr:String):Boolean - { - if (substr.length > str.length) return false; - return (str.substr(0, substr.length) == substr); - } - - public static function StringEndsWith(str:String, substr:String):Boolean - { - if (substr.length > str.length) return false; - return (str.substr(str.length - substr.length, substr.length) == substr); - } - - public static function StringContains(str:String, substr:String):Boolean - { - return (str.indexOf(substr) !== -1); - } - - private static var vowelsAndH = { - "a":true, "A":true, - "e":true, "E":true, - "i":true, "I":true, - "o":true, "O":true, - "u":true, "U":true, - "h":true, "H":true - } - public static function StringStartsWithVowelOrH(s:String):Boolean - { - if (vowelsAndH[s.charAt(0)]) return true; - return false; - } - - public static function CopyObject(obj, except = null) - { - var i; - if (except == null) except = []; - if (obj is Array) { - var obj2 = []; - for (i = 0; i < obj.length; i++) { - obj2.push(Utils.CopyObject(obj[i])); - } - return obj2; - } - var ret:Object = {}; - for (i in obj) - { - if (except.indexOf(i) == -1) { - ret[i] = obj[i]; - } - } - - return ret; - } - public static function CopyToObject(objFrom, objTo, except = null) - { - if (except == null) except = []; - for (var i in objFrom) - { - if (except.indexOf(i) == -1) { - objTo[i] = objFrom[i]; - } - } - } - public static function CopyToObjectOnly(objFrom, objTo, only) - { - if (only == null) return; - for (var i in only) - { - if (objFrom.hasOwnProperty(only[i])) - { - objTo[only[i]] = objFrom[only[i]]; - } - } - } - - public static function ColorizeRGB(clip:MovieClip, r:int,g:int,b:int) - { - var cTransform = clip.transform.colorTransform; - cTransform.redOffset = r; - cTransform.greenOffset = g; - cTransform.blueOffset = b; - clip.transform.colorTransform = cTransform; - } - - public static function hex2rgb (hex):Object - { - var red = hex>>16; - var greenBlue = hex-(red<<16) - var green = greenBlue>>8; - var blue = greenBlue - (green << 8); - return({r:red, g:green, b:blue}); - } - - public static function RGBtoHEX(r, g, b) { - return r << 16 | g << 8 | b; - } - - /** - * NOTE: An alpha of 1 will make the object a solid color (good for silhouettes) - */ - public static function TintDisplayObject(obj:DisplayObject, color:uint = 0xffffff, alpha:Number = 1.0) - { - var cTint:Color = new Color(); - cTint.setTint(color, alpha); - obj.transform.colorTransform = cTint; - } - - // given an origin (ox, oy) and a look at point (tx, ty), - // and a clip with the given number of rotation states, which - // rotation should we pick? - public static function Rotation(ox, oy, tx, ty, rotations) - { - var delta:Point = new Point(tx - ox, ty - oy); - if (Point.distance(delta, new Point(0.0, 0.0)) < 0.00001) { - delta.y = -1.0; - } - var d = ( - (-Math.floor( - /* calculate the rotation and scale it */ - Math.atan2(delta.y, delta.x) / (Math.PI * 2.0) * rotations - + 0.5 // add 0.5 and take the floor (round to closest int) - ) - + rotations) // atan2 returns in the range -pi to pi, measured ccw from +x, - // we negate it and add rotations again to get it in the range - // [0, rotations] - % rotations) + 1; // add 1 to reference frames - return d; - } - /* performs multiple operations asynchronously, but wait for them all to finish: - * instead of calling a bunch of functions and passing callbacks, pass those callbacks to WaitForFunctions - * and use ret.callbacks[0], ret.callbacks[1], etc... as the callbacks - * this will wait until every command is complete and call all the callbacks at once. - * - * For instance, to load multiple graphics packs asynchronously and wait for them all to finish, - * call var ret = WaitForFunctions([DoneLoading, null, null, null]); to generate - * ret.callbacks[0]..ret.callbacks[3], and pass these to 4 calls to LoadExternalGraphics. - * When these 4 calls complete, the provided 4 functions will be called with the arguments returned - * from the callbacks (in this case, only DoneLoading will be called since the - * other callbacks are null). - */ - public static function WaitForFunctions(...funcs):Object - { - var ret:Object = {}; - // has a callback been hit? - ret.hit = new Array(funcs.length); - // what were the original arguments the callback was called with - ret.args = new Array(funcs.length); - // a list of the artifical callbacks we are providing - ret.callbacks = new Array(funcs.length); - // the real callbacks - ret.funcs = funcs; - ret.done = false; - - ret.immediate = []; - - for (var i = 0; i < funcs.length; i++) { - // we have to setup this temp callback in another function, because the anon function's - // activation object will contain the current scope, meaning that the variable - // i will be updated in each function; if we do it in a seperate function each - // activation object will reference a different i - ret.callbacks[i] = Utils.SetupFunction(ret, i); - } - return ret; - } - - /** - * Returns the standard money format for an integer amount - */ - public static function FormatCurrency(amount:int, symbol:String = "$"):String - { - var afterDecimal:String = (amount % 100).toString(); - while (afterDecimal.length < 2) afterDecimal = "0" + afterDecimal; //mmmm string concatenation - - var beforeDecimal:String; - if (amount > 100) - { - beforeDecimal = Math.floor(amount/100).toString(); - } - else - { - beforeDecimal = "0"; - } - - return symbol + beforeDecimal + "." + afterDecimal; - } - - public static function FormatNumber(amount){ - var whole = Math.floor(amount); - // convert the number to a string - var amount_str:String = String(whole); - var total_str:String = String(amount); - - var number_array:Array = []; - var start:Number; - var end:Number = amount_str.length; - while (end > 0) { - start = Math.max(end - 3, 0); - number_array.unshift(amount_str.slice(start, end)); - end = start; - } - - var point = total_str.indexOf("."); - - var ret = number_array.join(","); - if (point != -1 && point < total_str.length) - { - ret += total_str.substr(point); - } - - return ret; - } - - protected static function SetupFunction(ret, i):Function - { - var a:Function = - function(...rest) { - if (ret.immediate[i]) ret.immediate[i].apply(null, rest); - ret.hit[i] = true; - ret.args[i] = rest; - var ok:Boolean = true; - var j; - for (j = 0; j < ret.hit.length; j++) { - if (!ret.hit[j]) { ok = false; break; } - } - if (ok && !ret.done) { - ret.done = true; - for (j = 0; j < ret.funcs.length; j++) { - if (ret.funcs[j] != null) ret.funcs[j].apply(null, ret.args[j]); - } - } - }; - return a; - } - - // useful for the paned dialogs to show a certain pane/button - public static function OnlyVisible(obj, set:Array, index:int) - { - for (var i in set) { - if (i != index) { - obj[set[i]].visible = false; - } else { - obj[set[i]].visible = true; - } - } - } - public static function AllVisible(obj, set:Array) - { - for (var i in set) { - obj[set[i]].visible = true; - } - } - // set one of a list of tabs to be enabled - public static function OnlyToggled(obj, set:Array, index:int) - { - for (var i in set) { - if (i != index) { - obj[set[i]].SetToggled(false); - } else { - obj[set[i]].SetToggled(true); - } - } - } - // get the frame number of a label in the timeline - public static function GetLabelFrame(mc, name:String):int - { - for (var l in mc.currentLabels) { - if (mc.currentLabels[l].name == name) return mc.currentLabels[l].frame; - } - return 1; - } - // generate a quick text field of a certain color/style - public static function BasicTextField(color:uint, - size:int, - font:String, - text:String, - additional:Object = null, - align = "left"):TextField - { - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.align = align; - if (additional != null) for (var a in additional) f[a] = additional[a]; - f.font = font; - f.color = color; - f.size = size; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.text = text; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - return t; - } - public static function var_dump(_obj, name = "Dump") - { - _strace(name + " " + (_obj) + " {"); - flash.utils.describeType(_obj); - var varList:XMLList = flash.utils.describeType(_obj)..variable; - - for(var i:int; i < varList.length(); i++) - { - //Show the name and the value - _strace(" " + varList[i].@name+' = '+ _obj[varList[i].@name]); - } - _strace("}"); - } - - public static function SetChildFrames(parentClip, frame, exclude = null) - { - if (parentClip is MovieClip && parentClip.name != exclude) - { - parentClip.gotoAndStop(frame); - for (var i = 0; i < parentClip.numChildren; i++) - { - Utils.SetChildFrames(parentClip.getChildAt(i), frame, exclude); - } - } - } - - public static function SetChildFramesNoParent(parentClip, frame, exclude = null) - { - if (parentClip is MovieClip && parentClip.name != exclude) - { - for (var i = 0; i < parentClip.numChildren; i++) - { - Utils.SetChildFrames(parentClip.getChildAt(i), frame, exclude); - } - } - } - - //modifies the array passed as parameter, following the MO of the built in Array.sort() - public static function insertionSort(array:Array, compareFunction:Function):void - { - for(var i:int=1; i < array.length; i++) - { - var value:Object = array[i]; - var k:int=i-1; - while( k >= 0 && compareFunction(array[k], value) == -1) - { - array[k+1]=array[k]; - k--; - } - array[k+1]=value; - } - } - - - public static function Screenshot(sourceClip, receiverURL, filename) - { - - var jpgSource:BitmapData; - - if (sourceClip is Stage) - { - jpgSource = new BitmapData (sourceClip.stageWidth, sourceClip.stageHeight); - } else { - jpgSource = new BitmapData (sourceClip.width, sourceClip.height); - } - - jpgSource.draw(sourceClip); - - var jpgEncoder:JPGEncoder = new JPGEncoder(85); - var jpgStream:ByteArray = jpgEncoder.encode(jpgSource); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - var jpgURLRequest:URLRequest = new URLRequest(receiverURL+"?name="+filename); - jpgURLRequest.requestHeaders.push(header); - jpgURLRequest.method = URLRequestMethod.POST; - jpgURLRequest.data = jpgStream; - navigateToURL(jpgURLRequest, "_blank"); - - } - - - public static function SetColors(clip, color) - { - var colorTransform:ColorTransform; - - if (clip == null || color == null) return; - - if (clip.hasOwnProperty("outline") && clip.outline != null) - { - colorTransform = clip.outline.transform.colorTransform; - colorTransform.color = color.Outline; - clip.outline.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryOutline") && clip.secondaryOutline != null) - { - colorTransform = clip.secondaryOutline.transform.colorTransform; - colorTransform.color = color.LightOutline; - clip.secondaryOutline.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("color") && clip.color != null) - { - colorTransform = clip.color.transform.colorTransform; - colorTransform.color = color.Primary; - clip.color.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryColor") && clip.secondaryColor != null) - { - colorTransform = clip.secondaryColor.transform.colorTransform; - colorTransform.color = color.Secondary; - clip.secondaryColor.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("shadow") && clip.shadow != null) - { - colorTransform = clip.shadow.transform.colorTransform; - colorTransform.color = color.Shadow; - clip.shadow.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryShadow") && clip.secondaryShadow != null) - { - colorTransform = clip.secondaryShadow.transform.colorTransform; - colorTransform.color = color.SecondaryShadow; - clip.secondaryShadow.transform.colorTransform = colorTransform; - } - } - /* returns a rect with the x, and y pos to center and the scaleX and scaleY as width and height */ - public static function GetUniformScaleRect(clip:MovieClip, maxWidth, maxHeight) - { - var rect:Rectangle = new Rectangle(0,0,0,0); - - var widthScale = Math.min(maxWidth / clip.width, 999); - var heightScale = Math.min(maxHeight / clip.height, 999); - - var scale = 1; - if (widthScale > heightScale) - { - scale = heightScale; - } else { - scale = widthScale; - } - - rect.width = clip.width * scale; - rect.height = clip.height * scale; - - var pb = clip.getBounds(clip); - var xadjust = -pb.left * scale; - var yadjust = -pb.top * scale; - - rect.x = xadjust + (maxWidth - rect.width) / 2; - rect.y = yadjust + (maxHeight - rect.height) / 2; - - rect.width = scale; - rect.height = scale; - - return rect; - } - - public static function Dec2Hex(d) - { - var chars:String = "0123456789ABCDEF"; - var str:String = ""; - while (d > 0 || str.length < 2) - { - var digit = d % 16; - d = (d - digit) / 16; - str = chars.charAt(digit) + str; - } - return str; - } - - public static function Hex2Dec(h:String) - { - var chars:String = "0123456789ABCDEF"; - var val = 1; - var res = 0; - for (var i = h.length - 1; i >= 0; i--) - { - res += chars.indexOf(h.substr(i, 1)) * val; - val *= 16; - } - return res; - } - - public static function ShallowCopyArray(array:Array) - { - if (!array) return null; - - var newArray:Array = []; - for (var i:int = 0; i < array.length; i++) - { - newArray.push(array[i]); - } - return newArray; - } - - /* Note: Will fail if any items in either array have reference type semantics (unless they point to the same object) - * (as opposed to value type semantics) - */ - public static function areEqual(a:Array,b:Array):Boolean { - if(a.length != b.length) { - return false; - } - var len:int = a.length; - for(var i:int = 0; i < len; i++) { - if(a[i] !== b[i]) { - return false; - } - } - return true; - } - - /* Note: Will fail if any items in either array have reference type semantics - * (as opposed to value type semantics) - */ - public static function objectsAreEqual(a:Object,b:Object):Boolean { - - for (var i in a) - { - if (!b.hasOwnProperty(i) || a[i] != b[i]) return false; - } - - return true; - } - - public static function DeepCopyClone (source : Object) : * - { - var array : ByteArray = new ByteArray (); - - array.writeObject (source); - array.position = 0; - - return array.readObject (); - } - - // {a:1, b:2} => [1,2] - public static function ObjectValues (obj:Object):Array { - var array = []; - for (var key in obj) array.push(obj[key]); - return array; - } - - // {a:1, b:2} => ["a","b"] - public static function ObjectKeys (obj:Object):Array { - var array = []; - for (var key in obj) array.push(key); - return array; - } - - // normal random variate generator; mean m, standard deviation s - public static function BoxMullerRandomNormal(m:Number, s:Number) : Number - { - var x1, x2, w, y1:Number; - var y2:Number; - var use_last:Boolean = false; - - if (use_last == true) /* use value from previous call */ - { - y1 = y2; - use_last = false; - } - else - { - do { - x1 = 2.0 * Math.random() - 1.0; - x2 = 2.0 * Math.random() - 1.0; - w = x1 * x1 + x2 * x2; - } while ( w >= 1.0 ); - - w = Math.sqrt( (-2.0 * Math.log( w ) ) / w ); - y1 = x1 * w; - y2 = x2 * w; - use_last = true; - } - - return( m + y1 * s ); - } - - public static function SanitizeNumber(n) - { - if (n is Number) - { - if (n == Number.NEGATIVE_INFINITY || n == Number.POSITIVE_INFINITY || n == Number.NaN) return 0; - } - return n; - } - - public static function IsNumberInvalid(n) - { - if (n is Number) - { - if (n == Number.NEGATIVE_INFINITY || n == Number.POSITIVE_INFINITY || n == Number.NaN) return true; - } - return false; - } - - public static function LimitNumberToMax(n) - { - if (n == Number.POSITIVE_INFINITY) return Number.MAX_VALUE; - return n; - } - - /* - value= Math.round(20/7); - value= int((20/7)*10)/10; - value= int((20/7)*100)/100; - value= int((20/7)*1000)/1000; - value= int((20/7)*10000)/10000; - */ - public static function RoundToDecimalPlaces(number:Number, places:int) - { - return Math.round((number)*Math.pow(10,places))/Math.pow(10,places); - } - - public static function GetShuffledArray(a:Array) : Array - { - var r:Array = a.concat(); - r.sort(randomSort); - return r; - } - - ///Convenience function since I keep forgetting the name of randomSort (hint: it's randomSort) - public static function ShuffleArray(a:Array) - { - a.sort(randomSort); - } - - public static function PickRandom(a:Array) - { - return a[Math.floor(Math.random() * a.length)]; - } - - /** - * Returns n elements of array a, up to a maximum of a's length. - * If forceCopy is set, the returned array will always be a new instance. - */ - public static function PickRandomSet(a:Array, n:int, forceCopy:Boolean=false):Array - { - if (a.length <= n || a.length == 0) - { - if (forceCopy) return a.concat(); - else return a; - } - if (n == 1) return [PickRandom(a)]; - - var shuffled:Array = GetShuffledArray(a); - return shuffled.slice(0, n); - } - - /** - * Does not randomly sort an array! To do that, Use the default array.sort with this as its argument. - * If you want a new, shuffled array, use GetShuffledArray - */ - public static function randomSort(a:*, b:*) : Number - { - if (Math.random() < 0.5) return -1; - else return 1; - } - - /** - * Returns the union of arr1 and arr2. If the elements are not primitive types, you'll need to provide a sorting function. - * If inPlace, a1 and a2 will be sorted. - * If they already contain duplicates, then all bets are off. - */ - public static function MergeArrays(arr1:Array, arr2:Array, sortFunc:Function = null, inPlace:Boolean = false) : Array - { - var ret:Array = []; - var a1:Array = (inPlace) ? arr1 : arr1.slice(); - var a2:Array = (inPlace) ? arr2 : arr2.slice(); - - var len1:uint = a1.length; - var len2:uint = a2.length; - var i1:uint = 0; - var i2:uint = 0; - - //Boring cases - if (len1 == 0 && len2 == 0) return ret; - if (len1 == 0) return (inPlace) ? a2.slice() : a2; - if (len2 == 0) return (inPlace) ? a1.slice() : a1; - - if (sortFunc) - { - a1.sort(sortFunc); - a2.sort(sortFunc); - } - else - { - a1.sort(); - a2.sort(); - } - - while (i1 < len1) - { - //add all from a2 up to a1[i1] - while (i2 < len2 && a2[i2] <= a1[i1]) - { - ret.push(a2[i2]); - i2 += 1; - } - if (ret.length == 0 || a1[i1] != ret[ret.length-1]) ret.push(a1[i1]); - i1 += 1; - } - - while (i2 < len2) ret.push(a2[i2]); - - return ret; - } - - public static function ConvertToHHMMSS(seconds:Number):String - { - var s:Number = seconds % 60; - var m:Number = Math.floor((seconds % 3600 ) / 60); - var h:Number = Math.floor(seconds / (60 * 60)); - - var hourStr:String = (h == 0) ? "" : DoubleDigitFormat(h) + ":"; - var minuteStr:String = DoubleDigitFormat(m) + ":"; - var secondsStr:String = DoubleDigitFormat(s); - - return hourStr + minuteStr + secondsStr; - } - - public static function DoubleDigitFormat(num:uint):String - { - if (num < 10) - { - return ("0" + num); - } - return String(num); - } - - public static function CapitolizeString(str:String) : String - { - var firstChar:String = str.substr(0, 1); - var restOfString:String = str.substr(1, str.length); - - return firstChar.toUpperCase()+restOfString.toLowerCase(); - } - - // ^ Nice spelling, goof! - public static function CapitalizeString(str:String) : String - { - return CapitolizeString(str); - } - - public static function GetListString(listStrings:Array) : String - { - var andString:String = "&"; - var count:int = 0; - - var listString:String = ""; - for (var i = 0; i < listStrings.length; i++) - { - if (count > 0 && listStrings.length == 2) listString += " "+andString+" "; // For just 2 items - else if (count == listStrings.length-1 && listStrings.length > 2) - { - // For adding "and" at the end of 3+ items. It is: ", and $(item)" - var endingString:String = ""; - endingString = endingString.replace("$(item)", listStrings[i]); - listString += endingString; - count++; - continue; - } - else if (count > 0) listString += ", "; // Comma separated list - - listString += listStrings[i]; - count++; - } - - return listString; - } - - /* - * Flash doesn't like the way MySQL prints dates (2016-06-02 13:00:00) - * "The year month and day terms can be separated by a forward slash (/) or by spaces, but never by a dash (-)." - */ - public static function ParseDate (dateString:String) : Date - { - var pattern:RegExp = /-/g; - var date = new Date(); - dateString = dateString.replace(pattern, "/"); - date.setTime(Date.parse(dateString)); - return date; - } - - /* - * For display only, not intended to be read by ParseDate - * Tuesday, June 7th, 2016 at 10:32 AM - */ - public static function FormatDate (date:Date) : String - { - var f:DateTimeFormatter = new DateTimeFormatter("en-US"); - var dateStr:String; - var lastChar:String; - - //Flash can't do "1st", "2nd", etc - - f.setDateTimePattern("d"); - dateStr = f.format(date); - lastChar = dateStr.charAt(dateStr.length - 1); - - if (lastChar == "1" && dateStr != "11") dateStr += "st"; - else if (lastChar == "2" && dateStr != "12") dateStr += "nd"; - else if (lastChar == "3" && dateStr != "13") dateStr += "rd"; - else dateStr += "th"; - - f.setDateTimePattern("EEEE, MMMM '" + dateStr + "', yyyy 'at' h:mm a"); - return f.format(date); - } - - /* Simply counts the number of properties on the object - */ - public static function CountObjectParameters(obj:Object):int - { - var cnt:int=0; - - for (var s:String in obj) cnt++; - - return cnt; - } - - /** - * For when shit gets real - */ - public static function PrintStackTrace() - { - try { - throw new Error('StackTrace'); - } catch (e:Error) { - _strace(e.getStackTrace()); - } - } - } -} \ No newline at end of file diff --git a/org/aszip/compression/CompressionMethod.as b/org/aszip/compression/CompressionMethod.as deleted file mode 100644 index 42fe7a0..0000000 --- a/org/aszip/compression/CompressionMethod.as +++ /dev/null @@ -1,17 +0,0 @@ -package org.aszip.compression - -{ - - /** - * The CompressionMethod class lets you choose the compression algorithms used for the files in the ZIP. - */ - public class CompressionMethod - - { - - public static var GZIP:String = 'GZIP'; - public static var NONE:String = 'NONE'; - - } - -} \ No newline at end of file diff --git a/org/aszip/crc/CRC32.as b/org/aszip/crc/CRC32.as deleted file mode 100644 index fcbc4f0..0000000 --- a/org/aszip/crc/CRC32.as +++ /dev/null @@ -1,63 +0,0 @@ -/** -* AS3 CRC32 algorithm implementation -*/ - -package org.aszip.crc -{ - - import flash.utils.ByteArray; - - public class CRC32 { - - private var crc32:int; - private static var CRCTable:Array = initLookupTable(); - - private static function initLookupTable ():Array - { - - var polynomial:int = 0xEDB88320; - var CRC32Table:Array = new Array(256); - - var i:int = 256; - var j:int = 8; - - while ( i-- ) - - { - - var crc:int = i; - - while ( j-- ) crc = (crc & 1) ? (crc >>> 1) ^ polynomial : (crc >>> 1); - - j = 8; - - CRC32Table [ i ] = crc; - - } - - return CRC32Table; - - } - - public function generateCRC32 ( pBytes:ByteArray ):void - { - - var length:int = pBytes.length; - - var crc:int = ~crc32; - - for ( var i:int = 0; i < length; i++ ) crc = ( crc >>> 8 ) ^ CRCTable[ pBytes[i] ^ (crc & 0xFF) ]; - - crc32 = ~crc; - - } - - public function getCRC32 ():int - { - - return crc32 & 0xFFFFFFFF; - - } - - } -} \ No newline at end of file diff --git a/org/aszip/encoding/PNGEnc.as b/org/aszip/encoding/PNGEnc.as deleted file mode 100644 index 9847cd6..0000000 --- a/org/aszip/encoding/PNGEnc.as +++ /dev/null @@ -1,218 +0,0 @@ -/** -* PNG encoding class from kaourantin.net, optimised by 5etdemi.com/blog -* @author kaourantin -* @version 0.1 -*/ - -package org.aszip.encoding -{ - import flash.utils.ByteArray; - import flash.display.BitmapData; - import flash.utils.getTimer; - import flash.geom.Rectangle; - - public class PNGEnc { - - public static function encode(img:BitmapData, type:uint = 0):ByteArray { - - - - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - if(img.transparent || type == 0) - { - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - } - else - { - IHDR.writeUnsignedInt(0x08020000); //24bit RGB - } - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - - switch(type) - { - case 0: - writeRaw(img, IDAT); - break; - case 1: - writeSub(img, IDAT); - break; - } - - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - - - - return png; - } - - private static function writeRaw(img:BitmapData, IDAT:ByteArray):void - { - var h:int = img.height; - var w:int = img.width; - var transparent:Boolean = img.transparent; - - for(var i:int=0;i < h;i++) { - // no filter - if ( !transparent ) { - var subImage:ByteArray = img.getPixels( - new Rectangle(0, i, w, 1)); - //Here we overwrite the alpha value of the first pixel - //to be the filter 0 flag - subImage[0] = 0; - IDAT.writeBytes(subImage); - //And we add a byte at the end to wrap the alpha values - IDAT.writeByte(0xff); - } else { - IDAT.writeByte(0); - var p:uint; - for(var j:int=0;j < w;j++) { - p = img.getPixel32(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - (p>>>24))); - } - } - } - } - - private static function writeSub(img:BitmapData, IDAT:ByteArray):void - { - var r1:uint; - var g1:uint; - var b1:uint; - var a1:uint; - - var r2:uint; - var g2:uint; - var b2:uint; - var a2:uint; - - var r3:uint; - var g3:uint; - var b3:uint; - var a3:uint; - - var p:uint; - var h:int = img.height; - var w:int = img.width; - - for(var i:int=0;i < h;i++) { - // no filter - IDAT.writeByte(1); - if ( !img.transparent ) { - r1 = 0; - g1 = 0; - b1 = 0; - a1 = 0xff; - for(var j:int=0;j < w;j++) { - p = img.getPixel(j,i); - - r2 = p >> 16 & 0xff; - g2 = p >> 8 & 0xff; - b2 = p & 0xff; - - r3 = (r2 - r1 + 256) & 0xff; - g3 = (g2 - g1 + 256) & 0xff; - b3 = (b2 - b1 + 256) & 0xff; - - IDAT.writeByte(r3); - IDAT.writeByte(g3); - IDAT.writeByte(b3); - - r1 = r2; - g1 = g2; - b1 = b2; - a1 = 0; - } - } else { - r1 = 0; - g1 = 0; - b1 = 0; - a1 = 0; - for(var k:int=0;k < w;k++) { - p = img.getPixel32(k,i); - - a2 = p >> 24 & 0xff; - r2 = p >> 16 & 0xff; - g2 = p >> 8 & 0xff; - b2 = p & 0xff; - - r3 = (r2 - r1 + 256) & 0xff; - g3 = (g2 - g1 + 256) & 0xff; - b3 = (b2 - b1 + 256) & 0xff; - a3 = (a2 - a1 + 256) & 0xff; - - IDAT.writeByte(r3); - IDAT.writeByte(g3); - IDAT.writeByte(b3); - IDAT.writeByte(a3); - - r1 = r2; - g1 = g2; - b1 = b2; - a1 = a2; - } - } - } - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - for (var n:uint = 0; n < 256; n++) { - //var c:uint = n; - for (var k:uint = 0; k < 8; k++) { - if (n & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - var c:uint = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - 0xff] ^ (c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/org/aszip/saving/Download.as b/org/aszip/saving/Download.as deleted file mode 100644 index 52cbb0a..0000000 --- a/org/aszip/saving/Download.as +++ /dev/null @@ -1,14 +0,0 @@ -package org.aszip.saving - -{ - - public class Download - - { - - public static const ATTACHMENT:String = "attachment"; - public static const INLINE:String = "inline"; - - } - -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/flash/util/RectangleNode.as b/flash/util/RectangleNode.as new file mode 100644 index 0000000..6f31e44 --- /dev/null +++ b/flash/util/RectangleNode.as @@ -0,0 +1,178 @@ +package util { + import flash.geom.Rectangle; + + public class RectangleNode + { + public var Left:RectangleNode = null; + public var Right:RectangleNode = null; + public var Rect:Rectangle = null; + public var InUse:Boolean = false; + public var Removed:Boolean = false; + public var Parent:RectangleNode = null; + public var AllocationID = 0; + public var Host:RectanglePacker= null; + public var MinAllocationID = 0; + public var NodeID; + public static var NextNodeID = 0; + + public var DontRemove = false; + + public var LastAccessTime = 0; + + public var Flags = []; + + public var UpdateTo:RectangleNode = null; + + /* + public function get Removed() + { + return _Removed; + } + + public function set Removed(r) + { + this._Removed = r; + } + + public function get Host():RectanglePacker + { + return _Host; + } + public function set Host(p:RectanglePacker) + { + this._Host = p; + + if (_Left && _Left.Host != p) + { + throw new Error("bad left host"); + } + if (_Right && _Right.Host != p) + { + throw new Error("bad right host"); + } + if (_Parent && _Parent.Host != p) + { + throw new Error("bad parent host"); + } + + } + + public function get Left():RectangleNode + { + return _Left; + } + public function set Left(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad left host"); + } + _Left = n; + } + public function get Right():RectangleNode + { + return _Right; + } + public function set Right(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad right host"); + } + _Right = n; + } + + public function get Parent():RectangleNode + { + return _Parent; + } + public function set Parent(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad parent host"); + } + _Parent = n; + } + */ + public function get IsFreeSpace() + { + return Left == null && Right == null && !InUse; + } + public function UpdateLinksFromNode(node:RectangleNode) + { + if (node.Parent) + { + if (node.Parent.Left == node) + { + node.Parent.Left = this; + } + if (node.Parent.Right == node) + { + node.Parent.Right = this; + } + } + if (node.Left) + { + node.Left.Parent = this; + } + if (node.Right) + { + node.Right.Parent = this; + } + } + public function MakeFromNode(node:RectangleNode) + { + //_Host = node.Host; + Host = node.Host; + Left = node.Left; + Right = node.Right; + Parent = node.Parent; + AllocationID = node.AllocationID; + InUse = node.InUse; + MinAllocationID = node.MinAllocationID; + NodeID = node.NodeID; + Rect = node.Rect.clone(); + Removed = node.Removed; + DontRemove = node.DontRemove; + } + public function RectangleNode(x, y, w, h, host:RectanglePacker) + { + this.NodeID = NextNodeID++; + this.Host = host; + this.Rect = new Rectangle(x, y, w, h); + } + public function OutputJSON() + { + var node = {}; + node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; + node.in_use = InUse; + node.id = NodeID; + if (this.Left) node.left = this.Left.OutputJSON(); + if (this.Right) node.right = this.Right.OutputJSON(); + return node; + } + + public function ReadJSON(details) + { + details.new_node = this; + this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); + this.Removed = false; + + this.InUse = details.in_use; + + if (details.hasOwnProperty("right")) + { + this.Right = new RectangleNode(0, 0, 0, 0, this.Host); + Right.ReadJSON(details.right); + Right.Parent = this; + } + if (details.hasOwnProperty("left")) + { + this.Left = new RectangleNode(0, 0, 0, 0, this.Host); + Left.ReadJSON(details.left); + Left.Parent = this; + } + } + } +} diff --git a/flash/util/RectanglePacker.as b/flash/util/RectanglePacker.as new file mode 100644 index 0000000..597d7fd --- /dev/null +++ b/flash/util/RectanglePacker.as @@ -0,0 +1,562 @@ +package util { + import flash.geom.*; + import flash.display.BitmapData; + import flash.display.MovieClip; + import flash.text.TextField; + import flash.events.*; + import flash.sampler.StackFrame; + + public class RectanglePacker + { + protected var w:int; + protected var h:int; + protected var root:RectangleNode; + public var NextAllocationID = 0; + + public function get width():int { return w; } + public function get height():int { return h; } + + public function RectanglePacker(w, h) + { + this.w = w; + this.h = h; + root = new RectangleNode(0, 0, w, h, this); + root.AllocationID = -1; + } + protected var area = 0; + + protected var testRender:MovieClip = new MovieClip(); + + public function GetRoot():RectangleNode + { + return root; + } + + public function GetLeafNodes():Array + { + return GetLeafNodesInternal(root); + } + + protected function GetLeafNodesInternal(n:RectangleNode):Array + { + if (n.InUse) return [n]; + var ret:Array = new Array(); + if (n.Left) ret = GetLeafNodesInternal(n.Left); + if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); + return ret; + } + + public function GetUsedArea() + { + return area; + } + + public function get efficiency() + { + return area / (w * h); + } + + protected function RectCost(w, h) + { + if (w == 0 || h == 0) return 99999999; + return (Math.max(w, h) / Math.min(w, h)) * w * h; + } + + protected function EnumerateTree(r:RectangleNode = null, indent = "") + { + if (r == null) r = this.root; + var str = ""; + str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; + if (r.Left) str += EnumerateTree(r.Left, indent + " "); + if (r.Right) str += EnumerateTree(r.Left, indent + " "); + return str; + } + + /* + * Remove a list of nodes from the tree. + * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree + * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, + leaving the original objects intact (in case something still references them) + */ + public function RemoveNodes(nodes:Array, fullyDestroy = true) + { + + /* DEBUG CHECKS */ + /* + this.PerformDebugCheck(); + + var str = ""; + for (var i = 0; i < nodes.length; i++) + { + str += nodes[i].NodeID + "\n"; + } + + var orig = nodes.concat(); + + var strs = [str, EnumerateTree()]; + + RenderDetailsBox.StartTrack("PackRemoveTime"); + + for (var i = 0; i < nodes.length; i++) + { + var n:RectangleNode = nodes[i]; + if (n.Host != this) + { + throw new Error("bad host!"); + } + } + */ + /* END DEBUG CHECKS */ + + var i, n:RectangleNode, p:RectangleNode; + + // setup the Removed flag on every node that should be removed + // we also check at this time to see if any more nodes need to be removed, such as a parent of + // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + if (n.Host == this) + { + n.Removed = true; + + if (n.InUse) + { + // sum up the total removed area + area -= n.Rect.width * n.Rect.height; + } + + if (n.Parent != null) + { + p = n.Parent; + // check and see if the current node's parent still has any valid children + if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) + { + // all of the current nodes siblings are either being removed or are blank, so + // we can remove the parent too + if (p.Left.IsFreeSpace) + { + // the left child was empty space before, so we can remove it (if it wasn't + // empty space it is already being removed so it doesn't need to be added + // to the list) + if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); + } + if (p.Right.IsFreeSpace) + { + // the right child was empty space before, so we can remove it + if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); + } + if (p != root && nodes.indexOf(p) == -1) + { + // remove the parent node too (provided it isn't the root!) + nodes.push(p); + } + } + } + } + } + + // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, + // so go ahead and remove them + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + + if (n.Parent != null) + { + // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not + // also getting removed!) + p = n.Parent; + + if (!p.Removed) + { + if (p.Left && p.Right) + { + var newNode:RectangleNode; + if (p.Left.Removed && p.Right.Removed) + { + // both children were removed, but the parent wasn't, so the parent must be root + // (since we never remove the root) + if (p != root) + { + throw new Error("should be root"); + } + p.Left.Parent = null; + p.Right.Parent = null; + p.Left = null; + p.Right = null; + p.InUse = false; + } else if (!p.Left.Removed) { + // Right node removed, Left node not removed + if (!p.Left.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Right); + newNode.UpdateLinksFromNode(p.Right); + } + // Left node is used + p.Right.InUse = false; + p.Right.Left = null; + p.Right.Right = null; + p.Right.Removed = false; + } else { + throw new Error("should have been caught above!"); + } + } else { + // Left node removed, Right node not removed + if (!p.Right.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Left); + newNode.UpdateLinksFromNode(p.Left); + } + // Left node is used + //p.Left.Removed = true; + p.Left.InUse = false; + p.Left.Left = null; + p.Left.Right = null; + p.Left.Removed = false; + //p.Left.Parent = null; + } else { + throw new Error("should have been caught above!"); + } + } + } else { + // huh? how does n.Parent == p but p has no children? something went wrong + throw new Error("shouldn't have gotten here"); + } + } + } + //strs.push(EnumerateTree()); + } + } + + public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode + { + + var node:RectangleNode = FindSizedNode(w, h, root); + + if (node == null) + { + //UHOH, texture full + return null; + } + area += w * h; + node.InUse = true; + + var splitVertFirstCost = 0; + if (w < node.Rect.width) + { + splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); + } + + var splitHorizFirstCost = 0; + if (h < node.Rect.height) + { + splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); + } + + + + if (splitVertFirstCost <= splitHorizFirstCost) + { + node.Flags.push("SplitVertFirst"); + if (w < node.Rect.width) + { + node.Flags.push("SplitVert"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + if (h < node.Rect.height) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + } else { + node.Flags.push("SplitHorzFirst"); + if (h < node.Rect.height) + { + node.Flags.push("SplitVert"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + if (w < node.Rect.width) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + } + NextAllocationID++; + if (useInstead) + { + useInstead.MakeFromNode(node); + useInstead.UpdateLinksFromNode(node); + useInstead.Flags = node.Flags; + node = useInstead; + node.Flags.push("UseInstead"); + } + + //if (!CheckOKNode(node)) node.Flags.push("BadNode"); + + return node; + } + public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) + { + if (r == null) r = this.root; + if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) + { + var ancestor:RectangleNode = FindCommonNode(n, r); + throw new Error("bad node allocated!"); + return false; + } + var ok = true; + if (r.Left) ok = ok && CheckOKNode(n, r.Left); + if (r.Right) ok = ok && CheckOKNode(n, r.Right); + return ok; + } + + public function PerformDebugCheck() + { + DebugInternal(this.root); + } + + protected function DebugInternal(n:RectangleNode) + { + if (n.Host != this) + { + throw new Error("problem with host!"); + } + if (n.IsFreeSpace) + { + if (n.Left || n.Right) + { + throw new Error("shouldn't have children"); + } + } + if ((n.Left && !n.Right) || (n.Right && !n.Left)) + { + throw new Error("mismatched children"); + } + if (n.Left && n.Left.Parent != n) + { + throw new Error("left child has bad parent"); + } + if (n.Right && n.Right.Parent != n) + { + throw new Error("right child has bad parent"); + } + if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) + { + throw new Error("problem with parent"); + } + if (n.Left) DebugInternal(n.Left); + if (n.Right) DebugInternal(n.Right); + } + + public function FindCommonNode(a:RectangleNode, b:RectangleNode) + { + var aHistory = []; + var bHistory = []; + while (a != null) + { + aHistory.push(a); + a = a.Parent; + } + while (b != null) + { + bHistory.push(b); + b = b.Parent; + } + var i = aHistory.length - 1; + var j = bHistory.length - 1; + var same = null; + while (i >= 0 && j >= 0) + { + if (aHistory[i] == bHistory[j]) + { + same = aHistory[i]; + } else { + break; + } + i--; + j--; + } + return same; + } + + public function TestRender() + { + while (testRender.numChildren > 0) + { + testRender.removeChildAt(0); + } + testRender.graphics.clear(); + TestRenderNode(root, testRender); + return testRender; + } + protected function TestRenderNode(n:RectangleNode, m:MovieClip) + { + var g:MovieClip = new MovieClip(); + m.addChild(g); + g.graphics.lineStyle(1, 0, 1); + if (n.Left != null) TestRenderNode(n.Left, m); + if (n.Left != null) TestRenderNode(n.Right, m); + if (n.InUse) + { + g.graphics.beginFill(0xFFFF00, 0.2); + } + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + if (n.InUse) + { + g.graphics.endFill(); + var t:TextField = new TextField(); + t.text = n.NodeID; + t.x = n.Rect.x + n.Rect.width / 2.0; + t.y = n.Rect.y + n.Rect.height / 2.0; + g.addChild(t); + g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); + g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); + } + + } + public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) + { + if (n.InUse) + { + //_trace(Math.round(n.LastAccessTime / 1000)); + } + var p:RectangleNode = n.Parent; + if (p) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); + g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); + g.graphics.endFill(); + t.text = p.NodeID; + if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); + g.oldListener = function(e){MouseOver(p, g, t);}; + g.addEventListener(MouseEvent.CLICK, g.oldListener); + } + } + public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(0xFFFF00, 0.2); + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + g.graphics.endFill(); + t.text = n.NodeID; + } + protected function SplitVert(node:RectangleNode, leftWidth) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function SplitHoriz(node:RectangleNode, topHeight) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode + { + if (node.InUse) return null; + if (node.Rect.width >= w && node.Rect.height >= h) + { + if (node.Left != null && node.Right != null) + { + var t:RectangleNode = FindSizedNode(w, h, node.Left); + if (t != null) return t; + t = FindSizedNode(w, h, node.Right); + return t; + } else { + return node; + } + } + return null; + } + + public function LoadTree(details) + { + this.root = new RectangleNode(0, 0, 0, 0, this); + root.ReadJSON(details); + + this.NextAllocationID = 0; + this.area = 0; + + var queue:Array = new Array(); + queue.push(root); + while (queue.length > 0) + { + var node:RectangleNode = queue.shift(); + node.AllocationID = NextAllocationID; + node.MinAllocationID = NextAllocationID; + if (node.Left) queue.push(node.Left); + if (node.Right) queue.push(node.Right); + if (node.InUse) this.area += node.Rect.width * node.Rect.height; + } + NextAllocationID++; + } + + public function GetNodePath(node:RectangleNode) + { + var output:String = ""; + while (node != this.root) + { + output = (node == node.Parent.Left ? "l" : "r") + output; + node = node.Parent; + } + return output; + } + + public function GetNodeFromPath(path:String):RectangleNode + { + var node:RectangleNode = this.root; + for (var i = 0; i < path.length; i++) + { + if (!node) return null; + if (path.charAt(i) == "r") + { + node = node.Right; + } else { + node = node.Left; + } + } + return node; + } + } +} diff --git a/flash/util/Utils.as b/flash/util/Utils.as new file mode 100644 index 0000000..f792003 --- /dev/null +++ b/flash/util/Utils.as @@ -0,0 +1,389 @@ +package util +{ + import flash.display.*; + import flash.geom.*; + public class Utils + { + public static function GetChildren(clip:MovieClip):Array + { + var ret:Array = []; + for (var i = 0; i < clip.numChildren; i++) + { + ret.push(clip.getChildAt(i)); + } + return ret; + } + + /* + * angle difference + * (range -Math.PI to Math.PI) + */ + public static function GetAngleDiff(a, b) + { + var angleDiff = b - a; + + while (angleDiff > Math.PI) + { + angleDiff -= Math.PI * 2; + } + while (angleDiff < -Math.PI) + { + angleDiff += Math.PI * 2; + } + return angleDiff; + } + + /* + * angle difference + * (range 0 to Math.PI) + */ + public static function GetAngleDiffAbs(a, b) + { + var angleDiff = GetAngleDiff(a, b); + while (angleDiff < 0) + { + angleDiff += Math.PI * 2; + } + + if (angleDiff > Math.PI) + { + angleDiff = Math.PI * 2 - angleDiff; + } + + return angleDiff; + } + + public static function GetTransform(from:Matrix, to:Matrix) + { + var i:Matrix = from.clone(); + i.invert(); + var m:Matrix = to.clone(); + m.concat(i); + return m; + } + + public static function Decompose(m:Matrix) + { + var s:Point = ScaleFromMat(m); + m = m.clone(); + + var sxUnit = s.x >= 0 ? 1 : -1; + var syUnit = s.y >= 0 ? 1 : -1; + + m.scale(sxUnit, syUnit); + + //m.a /= sxUnit; + //m.d /= syUnit; + var rot = RotFromMat(m); + return {sx:s.x, sy:s.y, rot:rot}; + } + + public static function RotFromMat(m:Matrix) + { + return Math.atan2(-m.c, m.a); + } + + public static function ScaleFromMat(m:Matrix):Point + { + var xAxisX = m.a; + var xAxisY = m.c; + + var yAxisX = m.b; + var yAxisY = m.d; + + var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); + if (m.a < 0) sx *= -1; + + var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); + if (m.d < 0) sy *= -1; + + return new Point(sx, sy); + } + + public static function TransformRect(r:Rectangle, m:Matrix) + { + var p1:Point = new Point(r.left, r.top); + var p2:Point = new Point(r.right, r.top); + var p3:Point = new Point(r.left, r.bottom); + var p4:Point = new Point(r.right, r.bottom); + + p1 = m.transformPoint(p1); + p2 = m.transformPoint(p2); + p3 = m.transformPoint(p3); + p4 = m.transformPoint(p4); + + r.left = Math.min(p1.x, p2.x, p3.x, p4.x); + r.top = Math.min(p1.y, p2.y, p3.y, p4.y); + r.right = Math.max(p1.x, p2.x, p3.x, p4.x); + r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); + } + + public static function RoundRect(r:Rectangle) + { + r.left = Math.floor(r.left); + r.top = Math.floor(r.top); + r.right = Math.ceil(r.right); + r.bottom = Math.ceil(r.bottom); + } + + public static function ScaleRect(r:Rectangle, s) + { + r.left *= s; + r.top *= s; + r.right *= s; + r.bottom *= s; + } + + public static function RecursivelyStop(clip) + { + if (clip is MovieClip) + { + clip.stop(); + } + if (clip is DisplayObjectContainer) + { + for (var i = 0; i < clip.numChildren; i++) + { + RecursivelyStop(clip.getChildAt(i)); + } + } + } + + public static function WeirdGotoFrame(clip:MovieClip, frame) + { + var dir = clip.currentFrame > frame ? -1 : 1; + while (clip.currentFrame != frame) + { + RecurseDir(clip, dir); + } + } + + protected static function RecurseDir(clip:MovieClip, dir) + { + for (var i = 0; i < clip.numChildren; i++) + { + var child = clip.getChildAt(i); + if (child is MovieClip) + { + RecurseDir(child, dir); + } + } + if (dir == 1) + { + clip.nextFrame(); + } else { + clip.prevFrame(); + } + } + + protected static var tempSpace:BitmapData = null; + protected static var tempSpaceRect:Rectangle = new Rectangle(); + protected static var tempSpaceMatrix:Matrix = new Matrix(); + protected static var tempSpaceZero:Point = new Point(); + protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); + protected static var lastDrawOffset:Point = new Point(); + public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle + { + if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); + + var oldPad = 0; + var padAmount = 5; + + var ret:Rectangle = new Rectangle(); + + var baseBounds:Rectangle = clip.getBounds(clip); + + var boundsClip:DisplayObject = null; + if (clip is DisplayObjectContainer) + { + boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); + } + + if (boundsClip != null) + { + baseBounds = boundsClip.getBounds(clip); + } + + if (useMatrix) + { + TransformAABBRect(baseBounds, useMatrix); + } + + if (boundsClip != null) + { + return baseBounds; + } + + var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); + var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); + if (tempSpace == null) + { + tempSpace = new BitmapData(minW, minH, true, 0x0); + } + if (tempSpace.width < minW || tempSpace.height < minH) + { + tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); + } + + var r:Rectangle = new Rectangle(); + + baseBounds.left = Math.floor(baseBounds.left); + baseBounds.right = Math.ceil(baseBounds.right); + + baseBounds.top = Math.floor(baseBounds.top); + baseBounds.bottom = Math.ceil(baseBounds.bottom); + + var i; + + var needsChecking = true; + while (needsChecking) + { + needsChecking = false; + r.left = baseBounds.left - padAmount; + r.right = baseBounds.right + padAmount; + + r.top = baseBounds.top - padAmount; + r.bottom = baseBounds.bottom + padAmount; + + ret = r.clone(); + + tempSpaceRect.x = tempSpaceRect.y = 0; + tempSpaceRect.width = tempSpace.width; + tempSpaceRect.height = tempSpace.height; + tempSpace.fillRect(tempSpaceRect, 0x0); + + tempSpaceMatrix.identity(); + if (useMatrix) + { + tempSpaceMatrix.a = useMatrix.a; + tempSpaceMatrix.b = useMatrix.b; + tempSpaceMatrix.c = useMatrix.c; + tempSpaceMatrix.d = useMatrix.d; + tempSpaceMatrix.tx = useMatrix.tx; + tempSpaceMatrix.ty = useMatrix.ty; + } + tempSpaceMatrix.translate(-r.left, -r.top); + + lastDrawOffset.x = -r.left; + lastDrawOffset.y = -r.top; + tempSpace.draw(clip, tempSpaceMatrix); + + tempSpaceRect.width = 1; + tempSpaceRect.height = r.height; + + var sideMovedIn = 0; + for (i = 0; i < r.width; i++) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.left++; + sideMovedIn++; + } + } + if (ret.left < baseBounds.left - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.width - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.right--; + } + } + if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + sideMovedIn = 0; + tempSpaceRect.width = r.width; + tempSpaceRect.height = 1; + tempSpaceRect.x = 0; + for (i = 0; i < r.height; i++) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.top++; + sideMovedIn++; + } + } + if (ret.top < baseBounds.top - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.height - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.bottom--; + } + } + if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + } + return ret; + } + + public static function TransformAABBRect(r:Rectangle, m:Matrix) + { + var o1X = r.left; + var o1Y = r.top; + + var o2X = r.right; + var o2Y = r.top; + + var o3X = r.left; + var o3Y = r.bottom; + + var o4X = r.right; + var o4Y = r.bottom; + + var n1X = o1X * m.a + o1Y * m.c + m.tx; + var n1Y = o1X * m.b + o1Y * m.d + m.ty; + + var n2X = o2X * m.a + o2Y * m.c + m.tx; + var n2Y = o2X * m.b + o2Y * m.d + m.ty; + + var n3X = o3X * m.a + o3Y * m.c + m.tx; + var n3Y = o3X * m.b + o3Y * m.d + m.ty; + + var n4X = o4X * m.a + o4Y * m.c + m.tx; + var n4Y = o4X * m.b + o4Y * m.d + m.ty; + + r.left = Math.min(n1X, n2X, n3X, n4X); + r.right = Math.max(n1X, n2X, n3X, n4X); + + r.top = Math.min(n1Y, n2Y, n3Y, n4Y); + r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); + } + } +} diff --git a/job.py b/job.py index 989c991..77c09e8 100644 --- a/job.py +++ b/job.py @@ -3,6 +3,7 @@ import json from validate import * from args import * +import copy asset_src_schema = { "type":"object", @@ -69,19 +70,24 @@ base_path = os.path.join(self.out_dir, self.rel_path) if not os.path.exists(base_path): os.makedirs(base_path) + resource_names = [] for i,r in enumerate(resources): - path = os.path.join(base_path, "%s_%04d.png" % (self.name, i)) + resource_name = "%s_%04d.png" % (self.name, i) if len(resources) > 1 else self.name + ".png" + resource_names.append(resource_name) + path = os.path.join(base_path, resource_name) with open(path, "wb") as f: f.write(base64.b64decode(r)) if len(data) == 1: graphic_and_asset = {} (name, graphic_data) = data.items()[0] - graphic_and_asset = {"data":graphic_data} + graphic_and_asset = {"data":graphic_data, "resources":resource_names} with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps(graphic_and_asset)) else: + write_data = copy.deepcopy(data) + write_data["resources"] = resource_names with open(os.path.join(base_path, self.name + ".asset"), "w") as f: - f.write(pretty_dumps(data)) + f.write(pretty_dumps(write_data)) for name,details in data.iteritems(): with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps({"data":self.name + ".asset"})) diff --git a/old/Checkbox.as b/old/Checkbox.as deleted file mode 100644 index c5aaba2..0000000 --- a/old/Checkbox.as +++ /dev/null @@ -1,42 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - - public class Checkbox extends MovieClip - { - public var Enabled:Boolean = true; - public function Checkbox() - { - checkbox.gotoAndStop(1); - checkbox.addEventListener(MouseEvent.CLICK, Clicked); - } - - protected function Clicked(event) - { - if (!Enabled) return; - Toggle(); - if (OnClick != null) OnClick(OnClickParam); - } - - protected var checked = false; - public function set Checked(value) { checked = value; checkbox.gotoAndStop(checked ? 2 : 1); } - public function get Checked() { return checked; } - - public function set Text(value) { text.text = value; } - - public var OnClickParam; - public var OnClick; - - - public function Toggle() - { - checked = !checked; - checkbox.gotoAndStop(checked ? 2 : 1); - - - } - - } - -} diff --git a/old/GraphicExport-app.xml b/old/GraphicExport-app.xml deleted file mode 100644 index 5144634..0000000 --- a/old/GraphicExport-app.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - GraphicExport - 1.0 - GraphicExport - - GraphicExport - - - GraphicExport.swf - standard - false - true - false - portrait - auto - true - true - true - - - false - false - desktop extendedDesktop diff --git a/old/GraphicExport.exe b/old/GraphicExport.exe deleted file mode 100644 index 56315aa..0000000 --- a/old/GraphicExport.exe +++ /dev/null Binary files differ diff --git a/old/GraphicExport.fla b/old/GraphicExport.fla deleted file mode 100644 index 0b78ed7..0000000 --- a/old/GraphicExport.fla +++ /dev/null Binary files differ diff --git a/old/GraphicExport.swf b/old/GraphicExport.swf deleted file mode 100644 index 542db97..0000000 --- a/old/GraphicExport.swf +++ /dev/null Binary files differ diff --git a/old/NewGraphicDialog.as b/old/NewGraphicDialog.as deleted file mode 100644 index 152011c..0000000 --- a/old/NewGraphicDialog.as +++ /dev/null @@ -1,224 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - import flash.events.*; - import flash.filesystem.File; - import flash.net.FileFilter; - import Defs.GraphicDef; - import flash.text.engine.GraphicElement; - - public class NewGraphicDialog extends MovieClip - { - - public function NewGraphicDialog() - { - // constructor code - Init(); - } - - var typeButtons:Array = new Array(); - - public function Init() - { - graphicPath.text = "Path to Graphic Here"; - - this.removeChild(browseButton); - - var newBrowseButton = new UI_GenericBlueButton(); - newBrowseButton.Text = "Browse"; - newBrowseButton.OnClick = BrowseForFile; - newBrowseButton.x = browseButton.x + (newBrowseButton.width / 2); - newBrowseButton.y = browseButton.y + (newBrowseButton.height / 2); - addChild(newBrowseButton); - - var newTestButton = new UI_GenericBlueButton(); - newTestButton.Text = "Export"; - newTestButton.OnClick = TestFile; - newTestButton.x = testButton.x + (newTestButton.width / 2); - newTestButton.y = testButton.y + (newTestButton.height / 2); - addChild(newTestButton); - - this.removeChild(typePlaceholderButton); - - var typeX = typePlaceholderButton.x; - var typeY = typePlaceholderButton.y + (typePlaceholderButton.height / 2); - - - var typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Graphic (1)"; - typeButton.OnClick = function(){ SetType(1); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Skeletal (3)"; - typeButton.OnClick = function(){ SetType(3); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Scene (6)"; - typeButton.OnClick = function(){ SetType(6); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - animationCheckbox.Checked = true; - //browseButton - //typePlaceholderButton - //usesInput - //usesText.text = "" - } - - var usesInputDefaultText = "Comma Seperated List of Uses Here"; - - public static var fakeID = 9999999; - public function TestFile() - { - fakeID++; - var graphicName = graphicPath.text; - var graphicData = {id:fakeID,graphic:graphicPath.text,v:1,fs:0,p:0,type:selectedType}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new GraphicDef(graphicData); - - this.Hide(); - graphicExport.ExportItem(graphicDef); - } - - var selectedType = 1; - public function SetType(type:Number) - { - selectedType = type; - - for(var i = 0; i < typeButtons.length; i++) - { - typeButtons[i].Enabled = true; - } - - animationCheckbox.visible = false; - - switch(type) - { - case 1: { - typeButtons[0].Enabled = false; - animationCheckbox.visible = true; - break; - } - case 3: typeButtons[1].Enabled = false; break; - case 6: typeButtons[2].Enabled = false; break; - } - } - - var graphicExport:GraphicExport; - public function Show(parentClip) - { - this.graphicExport = parentClip; - - parentClip.addChild(this); - - SetType(selectedType); - - var graphicList = GameData.Instance().GraphicDefines; - - var usesString:String = ""; - var uniqueUseTypes:Array = new Array(); - for (var i = 0; i < graphicList.length; i++) - { - var graphicDef:GraphicDef = graphicList[i]; - var uses = graphicDef.ExportParams['uses']; - for (var usage in uses) - { - if (uniqueUseTypes[uses[usage]] == null) - { - uniqueUseTypes[uses[usage]] = uses[usage]; - usesString += uses[usage] + ", "; - } - } - } - - graphicPath.text = ""; - - } - - public function CloseClicked(event) - { - Hide(); - } - - public function Hide() - { - if (this.parent != null) this.parent.removeChild(this); - } - - public function BrowseForFile() - { - var file:File = new File(); - var swfTypeFilter:FileFilter = new FileFilter("SWF Files","*.swf"); - file.addEventListener(Event.SELECT, openFile); - file.browse([swfTypeFilter]); - } - - private function openFile(event:Event):void - { - _strace(event.target.nativePath); - var path:String = event.target.nativePath; - var pathParts:Array = path.split("Graphics\\"); - if (pathParts.length == 2) - { - var fileRemainder:String = pathParts[1]; - var withoutExtension:String = fileRemainder.split(".")[0]; - var pattern:RegExp = /\\/g; - withoutExtension = withoutExtension.replace(pattern, "/"); - _strace(withoutExtension); - graphicPath.text = withoutExtension; - - if (withoutExtension.indexOf("Backgrounds") > -1) - { - SetType(6); - } - - if (withoutExtension.indexOf("Monsters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Characters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Portraits") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Quest") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Equipment") > -1) - { - SetType(1); - } - - - } - } - - - } - -} diff --git a/old/PNGExportHelper.as b/old/PNGExportHelper.as deleted file mode 100644 index f8c4c9d..0000000 --- a/old/PNGExportHelper.as +++ /dev/null @@ -1,253 +0,0 @@ -package -{ - import flash.display.*; - import com.adobe.images.*; - import flash.utils.*; - import flash.net.*; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import flash.geom.Point; - - public class PNGExportHelper - { - public static var UseExpandedBitmaps = false; - public static var AlphaThreshold = 5; - - private static function ExpandBitmapBorders(bd:BitmapData, bgColor = 0x0, passes = 1):BitmapData - { - /* - var thresh:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - thresh.threshold(bd, bd.rect, new Point(), "<", (20 << 24), bgColor, 0xFF000000, true); - */ - var sampled:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - bd.lock(); - sampled.lock(); - - for (var y = 0; y < bd.height; y++) - { - for (var x = 0; x < bd.width; x++) - { - var oldVal:uint = bd.getPixel32(x, y); - var a:uint = (oldVal & 0xFF000000) >>> 24; - var rgb:uint = (oldVal & 0xFFFFFF); - if (a > AlphaThreshold) - { - sampled.setPixel32(x, y, (0xFF << 24) | rgb); - } - else - { - sampled.setPixel32(x, y, bgColor); - } - } - } - sampled.unlock(); - bd.unlock(); - - return ExpandBitmapBordersInternal(sampled, bgColor, passes); - } - - private static function ExpandBitmapBordersInternal(bd:BitmapData, bgColor, passes):BitmapData - { - var output:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - - var scale = 16; - var scaled:BitmapData = new BitmapData(bd.width/scale, bd.height/scale, true, bgColor); - var mat:Matrix = new Matrix(); - mat.scale(1/scale, 1/scale); - scaled.draw(bd, mat, null, null, null, true); - - output.lock(); - - var colors:Array = new Array(); - var weights:Array = new Array(); - - for (var oy = 0; oy < scaled.height; oy++) - { - - for (var ox = 0; ox < scaled.width; ox++) - { - - var scaledVal:uint = scaled.getPixel32(ox, oy); - var scaleda:uint = (scaledVal & 0xFF000000) >>> 24; - if (scaleda == 0 || scaleda == 255) - { - output.copyPixels(bd, new Rectangle(ox * scale, oy * scale, scale, scale), new Point(ox * scale, oy * scale)); - continue; - } else { - //_strace(scaleda+""); - } - - - for (var y = oy * scale; y < oy * scale + scale; y++) - { - for (var x = ox * scale; x < ox * scale + scale; x++) - { - var oldVal:uint = bd.getPixel32(x, y); - var a:uint = (oldVal & 0xFF000000) >>> 24; - var rgb:uint = (oldVal & 0xFFFFFF); - - if (a == 0 && rgb == bgColor) - { - colors.length = 0; - weights.length = 0; - - for (var y1 = y - 2; y1 <= y + 2; y1++) - { - for (var x1 = x - 2; x1 <= x + 2; x1++) - { - var dist = Math.abs(x1 - x) + Math.abs(y1 - y); - if (dist >= 3) continue; - - if (x1 >= 0 && x1 < bd.width && y1 >= 0 && y1 < bd.height) - { - colors.push(bd.getPixel(x1, y1)); - weights.push(1 - dist * 0.2); - } - } - } - - var newVal = AveragePixels(colors, weights, bgColor); - if (newVal == null) - { - newVal = oldVal; - } - else - { - var newR:uint = (newVal & 0xFF0000) >> 16; - var newG:uint = (newVal & 0xFF00) >> 8; - var newB:uint = (newVal & 0xFF); - - if (newVal != 0 && colors.length >= 4) - { - var bp = true; - } - - var sorted = colors.sort(function(a, b) - { - var aR:uint = (a & 0xFF0000) >> 16; - var aG:uint = (a & 0xFF00) >> 8; - var aB:uint = (a & 0xFF); - - var bR:uint = (b & 0xFF0000) >> 16; - var bG:uint = (b & 0xFF00) >> 8; - var bB:uint = (b & 0xFF); - - var diffA = Math.abs(aR - newR) + Math.abs(aG - newG) + Math.abs(aB - newB); - var diffB = Math.abs(bR - newR) + Math.abs(bG - newG) + Math.abs(bB - newB); - - return diffA - diffB; - - }, Array.RETURNINDEXEDARRAY | Array.DESCENDING); - - var toRemove = Math.min(2, colors.length - 4); - var removed = 0; - for (var i = 0; i < colors.length; i++) - { - var index = sorted.indexOf(i + removed); - if (index < toRemove) - { - colors.splice(i, 1); - weights.splice(i, 1); - removed++; - i--; - if (removed == toRemove) break; - } - } - - var fixOutliersVal = AveragePixels(colors, weights, bgColor); - if (fixOutliersVal == null) newVal = (0xFF << 24) | newVal; - - newVal = (0xFF << 24) | fixOutliersVal; - } - - output.setPixel32(x, y, newVal); - } - else - { - output.setPixel32(x, y, oldVal); - } - } - } - }//end outer scaled x - }//End outer scaled y - - bd.unlock(); - output.unlock(); - - passes--; - if (passes > 0) - { - return ExpandBitmapBordersInternal(output, bgColor, passes); - } - else - { - return output; - } - } - - private static function AveragePixels(colors:Array, weights:Array, bgColor:uint):uint - { - var rTotal = 0; - var gTotal = 0; - var bTotal = 0; - - var wTotal = 0; - - for (var i = 0; i < colors.length; i++) - { - var color:uint = colors[i]; - var a:uint = (color & 0xFF000000) >>> 24; - var rgb:uint = (color & 0xFFFFFF); - - if (a == 0 && rgb == bgColor) - { - colors.splice(i, 1); - weights.splice(i, 1); - i--; - continue; - } - - var r:uint = (rgb & 0xFF0000) >>> 16; - var g:uint = (rgb & 0xFF00) >>> 8; - var b:uint = (rgb & 0xFF); - var w = weights[i]; - - rTotal += w * r; - gTotal += w * g; - bTotal += w * b; - - wTotal += w; - } - - if (wTotal == 0) - { - return null; - } - - rTotal /= wTotal; - gTotal /= wTotal; - bTotal /= wTotal; - - var rFinal = Math.max(0, Math.min(255, Math.round(rTotal))); - var gFinal = Math.max(0, Math.min(255, Math.round(gTotal))); - var bFinal = Math.max(0, Math.min(255, Math.round(bTotal))); - - return (uint(rFinal) << 16) | (uint(gFinal) << 8) | (uint(bFinal)); - } - - - - public static function GetExportPNG(bd:BitmapData):ByteArray - { - if (!UseExpandedBitmaps) return PNGEncoder.encode(bd); - - var expanded:BitmapData = ExpandBitmapBorders(bd, 0x0, 2); - - //var fr:FileReference = new FileReference(); - //fr.save(PNGEncoder.encode(expanded), "output.png"); - - return PNGEncoderWithAlpha.encode(expanded, bd); - } - - } -} \ No newline at end of file diff --git a/old/PreviewHolder.as b/old/PreviewHolder.as deleted file mode 100644 index 587bf68..0000000 --- a/old/PreviewHolder.as +++ /dev/null @@ -1,57 +0,0 @@ -package { - import flash.display.MovieClip; - - public class PreviewHolder extends MovieClip - { - - var startingWidth = 1024; - var startingHeight = 1024; - - public function PreviewHolder() - { - startingWidth = this.width; - startingHeight = this.height; - } - - var clips:Array = new Array(); - public function AddClip(clip) - { - clips.push(clip); - this.addChild(clip); - ArrangeClips(); - } - - public function ArrangeClips() - { - var numCols = Math.ceil(Math.sqrt(clips.length)); - var maxY = 0; - var maxX = 0; - var clipIndex = 0; - for (var row = 0; row < numCols; row++) - { - var clipX = 0; - var clipY = maxY; - for (var col = 0; col < numCols; col++) - { - if (clipIndex == clips.length) break; - clips[clipIndex].x = clipX; - clips[clipIndex].y = clipY; - clipX += clips[clipIndex].width; - var clipBottom = clips[clipIndex].y + clips[clipIndex].height; - if (clipBottom > maxY) maxY = clipBottom; - - var clipRight = clips[clipIndex].x + clips[clipIndex].width; - if (clipRight > maxX) maxX = clipRight; - clipIndex++; - } - } - - var scale = Math.min(startingWidth / maxX, startingHeight / maxY); - if (scale > 1) scale = 1; - - this.scaleX = this.scaleY = scale; - } - - } - -} diff --git a/old/Utils.as b/old/Utils.as deleted file mode 100755 index 02b4f12..0000000 --- a/old/Utils.as +++ /dev/null @@ -1,1202 +0,0 @@ -package old -{ - /* This class has functions similar to the Utils.as in the /flash/Dialogs folder. However, some of - * those functions are different here than in /flash/Dialogs/Utils.as for... reasons? flash folder reasons! - */ - import flash.utils.*; - import flash.net.*; - import flash.display.*; - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.geom.Point; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import flash.geom.ColorTransform; - import fl.motion.Color; - import fl.transitions.Tween; - import fl.transitions.easing.*; - import fl.transitions.TweenEvent; - import flash.net.navigateToURL; - import flash.external.ExternalInterface; - import flash.system.Capabilities; - import flash.filters.*; - import flash.filters.ColorMatrixFilter; - import com.adobe.images.JPGEncoder; - import flash.globalization.DateTimeFormatter; - - import djarts.utils.Base64; - import djarts.utils.PNGEnc; - import User.UserOptions; - - public class Utils - { - //["K","M","B","T","q", "Q", "s", "S","O","N","d","U","D","!","@","#","$","%","^","&","*"] - static var symbols = ["K","M","B","t","q", "Q", "s", "S","o","n","d","U","D","T","Qt","Qd","Sd","St","O","N","v","c"]; - static var divisors = []; - - public static function FormatBigNumber(number:*, round:Boolean=false):String - { - if (number < 0) return '-' + FormatBigNumber(Math.abs(number), round); - - var isWholeNumber = (Math.floor(number) == number); - round = round || isWholeNumber; - - if (number < 1000) - { - if (round) - { - return Math.round(number).toString(); - } - else - { - var decimalPlaces = (number >= 100) ? 1 : 2; // Below 100, show two decimal places. Above, only one. - var roundMult = Math.pow(10, decimalPlaces); - var rounded = Math.round(number); - var bigRounded = Math.round(number * roundMult); - var roundedDifferenceProportion = Math.abs(bigRounded / roundMult - rounded) / rounded; - - if (roundedDifferenceProportion < 0.001) - { - // Not a whole number, but the decimal places aren't worth showing - // Below also handles this, but is slower - return rounded.toString(); - } - else - { - var str:String = bigRounded.toString(); - str = str.substr(0, str.length - decimalPlaces) + "." + str.substr(str.length - decimalPlaces); - - while (str.charAt(str.length - 1) == "0") str = str.substr(0, str.length - 1); //should only ever happen once - if (str.charAt(str.length - 1) == ".") str = str.substr(0, str.length - 1); //probably won't happen at all - - return str; - } - } - } - - // Determine which symbol to use - var power = Math.floor(Math.log(number) / Math.log(1000)); - var index = Math.min(power-1, symbols.length-1); - var amount = number / Math.pow(1000, index+1); - var symbol = (index >= 0 && index < symbols.length) ? symbols[index] : ""; - - // If it's too big for a symbol (or if we just WANT to) - if (amount >= 1000 || UserOptions.ForceScientific) - { - // scientific notation - var power = Math.floor(Math.log(number) / Math.log(10)); - var num = number / Math.pow(10, power); - if (num == 10) { - num = 1; - power += 1; - } - var numString = "" + num; - numString = numString.substr(0, Math.min(4, numString.length)); - return numString + "e" + power; - - } - else - { - // Format with the symbol - // determine number of whole digits (will dictate how many decimals we show) - var whole = Math.floor(amount); - var amount_str:String = String(whole); - - var decimalDivider = 100/Math.pow(10,amount_str.length-1); - - //round to nearest decimal place - amount = int(amount*decimalDivider)/decimalDivider; - - var amountString:String = amount.toString(); - - var noDecimal:String = amountString.replace(".",""); - if (noDecimal.length == 2) - { - if (amountString.indexOf(".") != -1) amountString += "0"; - else amountString += ".0"; - } - else if (noDecimal.length == 1) amountString += ".00"; - - return amountString+symbol; // concat symbol - } - } - - private static var BigNumberRegex = new RegExp(/(\d*),?(\d*)(.*)/); - // Note-DG: This is mostly just used for definitions in the database, that don't require precision. - // This way we can define values in the database as 100B instead of 100000000000. - public static function ParseBigNumberString(number:String):Number - { - var regexArray:Array = BigNumberRegex.exec(number); - var magnitude = symbols.indexOf(regexArray[3]); - var thousands:Number; - if (regexArray[1]) { - thousands = regexArray[1]; - if (regexArray[2]) { // if numbers are split by comma, multiply by 1000 - thousands *= 1000; - } - } else { - thousands = 0; - } - var hundreds:Number = regexArray[2] ? regexArray[2] : 0; - - return (thousands + hundreds) * Math.pow(1000, magnitude + 1); - } - - public static function ParseNumberRange(range:String):Array - { - var split:Array = range.split(','); - return [Number(split[0]), Number(split[1])]; - } - - public static function DesaturateFilter() - { - var desatMatrix:Array = []; - var cmFilter; - - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // red - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // green - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // blue - desatMatrix = desatMatrix.concat([0, 0, 0, 1, 0]); // alpha - cmFilter = new ColorMatrixFilter(desatMatrix); - - return cmFilter; - } - - public static function GetUserAgent():String - { - try - { - var userAgent = ExternalInterface.call("window.navigator.userAgent.toString"); - var browser:String = "[Unknown Browser]"; - - if (userAgent.indexOf("Safari") != -1) - { - browser = "Safari"; - } - if (userAgent.indexOf("Firefox") != -1) - { - browser = "Firefox"; - } - if (userAgent.indexOf("Chrome") != -1) - { - browser = "Chrome"; - } - if (userAgent.indexOf("MSIE") != -1) - { - browser = "Internet Explorer"; - } - if (userAgent.indexOf("Opera") != -1) - { - browser = "Opera"; - } - } - catch (e:Error) - { - //could not access ExternalInterface in containing page - return "[No ExternalInterface]"; - } - - return browser; - } - - public static function GetScreenshot(stage:Stage):String { - var scale:Number = 0.25; - var result:String = null; - var blurFilter:BlurFilter = new BlurFilter(3, 3, BitmapFilterQuality.HIGH); - - var bData:BitmapData = new BitmapData(stage.stageWidth * scale, - stage.stageHeight * scale, false, 0x348400); - var matrix:Matrix = new Matrix(); - matrix.scale(scale, scale); - - bData.draw(stage, matrix); - bData.applyFilter(bData, bData.rect, new Point(0, 0), blurFilter); - - - var imgBytes:ByteArray = new JPGEncoder(80).encode(bData); - //var imgBytes:ByteArray = PNGEnc.encode(bData); - if (imgBytes) { - var screenshotBase64:String = Base64.encode(imgBytes); - if (screenshotBase64) { - result = screenshotBase64; - } - } - - return result; - } - - public static function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function PlayerVersion() - { - - // Get the player's version by using the getVersion() global function. - var versionNumber:String = Capabilities.version; - - // The version number is a list of items divided by "," - var versionArray:Array = versionNumber.split(","); - var length:Number = versionArray.length; - //for(var i:Number = 0; i < length; i++) _strace("versionArray["+i+"]: "+versionArray[i]); - - // The main version contains the OS type too so we split it in two - // and we'll have the OS type and the major version number separately. - var platformAndVersion:Array = versionArray[0].split(" "); - //for(var j:Number = 0; j < 2; j++) _strace("platformAndVersion["+j+"]: "+platformAndVersion[j]); - //_strace("-----"); - - var majorVersion:Number = parseInt(platformAndVersion[1]); - var minorVersion:Number = parseInt(versionArray[1]); - var buildNumber:Number = parseInt(versionArray[2]); - - return Number(majorVersion+"."+minorVersion); - } - - - public static function OpenLocalURLTop(url) - { - navigateToURL(new URLRequest(GameSettings.Approot+url), "_top" ); - } - - public static function OpenLocalURL(url) - { - navigateToURL(new URLRequest(GameSettings.Approot+url), "_blank" ); - } - - public static function OpenURL(url, window = "_blank") - { - navigateToURL(new URLRequest(url), window); - } - - public static var ExitFullScreenCallback; - - public static function WallPublish(title:String, desc1:String, desc2:String, image:String, url = null, action = null) - { - if (Utils.ExitFullScreenCallback) Utils.ExitFullScreenCallback(); - //_strace(title + "\n" + desc1 + "\n" + desc2 + "\n" + image + "\n"); - ExternalInterface.call("askToPublish", title, url, desc1, desc2, image, action); - - //if (Settings.Platform == Settings.HI5) { - //DialogManager.Instance().ShowMessageBox("The message was posted to your wall!", "", "OK", null); - //} - } - - public static function SendToRecipients(recipients:Array, description, data) - { - if (!GameSettings.IsFacebook) return; - - if (Utils.ExitFullScreenCallback) Utils.ExitFullScreenCallback(); - try { - ExternalInterface.call("sendToRecipients", recipients, description ,data); - } - catch (e) - { - _strace(e.message); - } - } - - - public static function GetFriendData() - { - try { - return ExternalInterface.call("pollInviteData"); - } - catch (e) - { - _strace(e.message); - } - } - - - public static function singleBounceEase(t:Number, b:Number, c:Number, d:Number):Number - { - t = t / d; - if (t < 0.7) { - t *= 1.0 / 0.65; - return c * (t * t) + b; - } - return c * (t * t) + b; - } - - public static function Finish(e:TweenEvent) - { - //_strace("done " + e.currentTarget.obj.x + " " + e.currentTarget.obj.y + " " + e.currentTarget.obj.scaleX + " " + e.currentTarget.obj.scaleY); - e.currentTarget.removeEventListener(TweenEvent.MOTION_FINISH, Finish); - } - public static function Popup(mc, startScale = 0.8, finishCallback = null) - { - var rect:Rectangle = mc.getRect(mc); - var targetX = mc.x; - var targetY = mc.y; - var centerX = mc.x + rect.left + mc.width / 2.0; - var centerY = mc.y + rect.top + mc.height / 2.0; - var startX = centerX - (rect.left + mc.width / 2.0) * startScale; - var startY = centerY - (rect.top + mc.height / 2.0) * startScale; - var tweenSX = new Tween(mc, "scaleX", singleBounceEase, startScale, 1.0, 4, false); - if (finishCallback) tweenSX.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenSY = new Tween(mc, "scaleY", singleBounceEase, startScale, 1.0, 4, false); - if (finishCallback) tweenSY.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenX = new Tween(mc, "x", singleBounceEase, startX, targetX, 4, false); - if (finishCallback) tweenX.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenY = new Tween(mc, "y", singleBounceEase, startY, targetY, 4, false); - if (finishCallback) tweenY.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - return [tweenSX, tweenSY, tweenX, tweenY]; - } - public static function StringSplit(s:String, delim:String, max:int = -1):Array - { - var ret:Array = s.split(delim); - if (max != -1) { - var more:String = ret.slice(max - 1).join(delim); - ret.splice(max - 1); - ret[max - 1] = more; - } - return ret; - } - - public static function StringStartsWith(str:String, substr:String):Boolean - { - if (substr.length > str.length) return false; - return (str.substr(0, substr.length) == substr); - } - - public static function StringEndsWith(str:String, substr:String):Boolean - { - if (substr.length > str.length) return false; - return (str.substr(str.length - substr.length, substr.length) == substr); - } - - public static function StringContains(str:String, substr:String):Boolean - { - return (str.indexOf(substr) !== -1); - } - - private static var vowelsAndH = { - "a":true, "A":true, - "e":true, "E":true, - "i":true, "I":true, - "o":true, "O":true, - "u":true, "U":true, - "h":true, "H":true - } - public static function StringStartsWithVowelOrH(s:String):Boolean - { - if (vowelsAndH[s.charAt(0)]) return true; - return false; - } - - public static function CopyObject(obj, except = null) - { - var i; - if (except == null) except = []; - if (obj is Array) { - var obj2 = []; - for (i = 0; i < obj.length; i++) { - obj2.push(Utils.CopyObject(obj[i])); - } - return obj2; - } - var ret:Object = {}; - for (i in obj) - { - if (except.indexOf(i) == -1) { - ret[i] = obj[i]; - } - } - - return ret; - } - public static function CopyToObject(objFrom, objTo, except = null) - { - if (except == null) except = []; - for (var i in objFrom) - { - if (except.indexOf(i) == -1) { - objTo[i] = objFrom[i]; - } - } - } - public static function CopyToObjectOnly(objFrom, objTo, only) - { - if (only == null) return; - for (var i in only) - { - if (objFrom.hasOwnProperty(only[i])) - { - objTo[only[i]] = objFrom[only[i]]; - } - } - } - - public static function ColorizeRGB(clip:MovieClip, r:int,g:int,b:int) - { - var cTransform = clip.transform.colorTransform; - cTransform.redOffset = r; - cTransform.greenOffset = g; - cTransform.blueOffset = b; - clip.transform.colorTransform = cTransform; - } - - public static function hex2rgb (hex):Object - { - var red = hex>>16; - var greenBlue = hex-(red<<16) - var green = greenBlue>>8; - var blue = greenBlue - (green << 8); - return({r:red, g:green, b:blue}); - } - - public static function RGBtoHEX(r, g, b) { - return r << 16 | g << 8 | b; - } - - /** - * NOTE: An alpha of 1 will make the object a solid color (good for silhouettes) - */ - public static function TintDisplayObject(obj:DisplayObject, color:uint = 0xffffff, alpha:Number = 1.0) - { - var cTint:Color = new Color(); - cTint.setTint(color, alpha); - obj.transform.colorTransform = cTint; - } - - // given an origin (ox, oy) and a look at point (tx, ty), - // and a clip with the given number of rotation states, which - // rotation should we pick? - public static function Rotation(ox, oy, tx, ty, rotations) - { - var delta:Point = new Point(tx - ox, ty - oy); - if (Point.distance(delta, new Point(0.0, 0.0)) < 0.00001) { - delta.y = -1.0; - } - var d = ( - (-Math.floor( - /* calculate the rotation and scale it */ - Math.atan2(delta.y, delta.x) / (Math.PI * 2.0) * rotations - + 0.5 // add 0.5 and take the floor (round to closest int) - ) - + rotations) // atan2 returns in the range -pi to pi, measured ccw from +x, - // we negate it and add rotations again to get it in the range - // [0, rotations] - % rotations) + 1; // add 1 to reference frames - return d; - } - /* performs multiple operations asynchronously, but wait for them all to finish: - * instead of calling a bunch of functions and passing callbacks, pass those callbacks to WaitForFunctions - * and use ret.callbacks[0], ret.callbacks[1], etc... as the callbacks - * this will wait until every command is complete and call all the callbacks at once. - * - * For instance, to load multiple graphics packs asynchronously and wait for them all to finish, - * call var ret = WaitForFunctions([DoneLoading, null, null, null]); to generate - * ret.callbacks[0]..ret.callbacks[3], and pass these to 4 calls to LoadExternalGraphics. - * When these 4 calls complete, the provided 4 functions will be called with the arguments returned - * from the callbacks (in this case, only DoneLoading will be called since the - * other callbacks are null). - */ - public static function WaitForFunctions(...funcs):Object - { - var ret:Object = {}; - // has a callback been hit? - ret.hit = new Array(funcs.length); - // what were the original arguments the callback was called with - ret.args = new Array(funcs.length); - // a list of the artifical callbacks we are providing - ret.callbacks = new Array(funcs.length); - // the real callbacks - ret.funcs = funcs; - ret.done = false; - - ret.immediate = []; - - for (var i = 0; i < funcs.length; i++) { - // we have to setup this temp callback in another function, because the anon function's - // activation object will contain the current scope, meaning that the variable - // i will be updated in each function; if we do it in a seperate function each - // activation object will reference a different i - ret.callbacks[i] = Utils.SetupFunction(ret, i); - } - return ret; - } - - /** - * Returns the standard money format for an integer amount - */ - public static function FormatCurrency(amount:int, symbol:String = "$"):String - { - var afterDecimal:String = (amount % 100).toString(); - while (afterDecimal.length < 2) afterDecimal = "0" + afterDecimal; //mmmm string concatenation - - var beforeDecimal:String; - if (amount > 100) - { - beforeDecimal = Math.floor(amount/100).toString(); - } - else - { - beforeDecimal = "0"; - } - - return symbol + beforeDecimal + "." + afterDecimal; - } - - public static function FormatNumber(amount){ - var whole = Math.floor(amount); - // convert the number to a string - var amount_str:String = String(whole); - var total_str:String = String(amount); - - var number_array:Array = []; - var start:Number; - var end:Number = amount_str.length; - while (end > 0) { - start = Math.max(end - 3, 0); - number_array.unshift(amount_str.slice(start, end)); - end = start; - } - - var point = total_str.indexOf("."); - - var ret = number_array.join(","); - if (point != -1 && point < total_str.length) - { - ret += total_str.substr(point); - } - - return ret; - } - - protected static function SetupFunction(ret, i):Function - { - var a:Function = - function(...rest) { - if (ret.immediate[i]) ret.immediate[i].apply(null, rest); - ret.hit[i] = true; - ret.args[i] = rest; - var ok:Boolean = true; - var j; - for (j = 0; j < ret.hit.length; j++) { - if (!ret.hit[j]) { ok = false; break; } - } - if (ok && !ret.done) { - ret.done = true; - for (j = 0; j < ret.funcs.length; j++) { - if (ret.funcs[j] != null) ret.funcs[j].apply(null, ret.args[j]); - } - } - }; - return a; - } - - // useful for the paned dialogs to show a certain pane/button - public static function OnlyVisible(obj, set:Array, index:int) - { - for (var i in set) { - if (i != index) { - obj[set[i]].visible = false; - } else { - obj[set[i]].visible = true; - } - } - } - public static function AllVisible(obj, set:Array) - { - for (var i in set) { - obj[set[i]].visible = true; - } - } - // set one of a list of tabs to be enabled - public static function OnlyToggled(obj, set:Array, index:int) - { - for (var i in set) { - if (i != index) { - obj[set[i]].SetToggled(false); - } else { - obj[set[i]].SetToggled(true); - } - } - } - // get the frame number of a label in the timeline - public static function GetLabelFrame(mc, name:String):int - { - for (var l in mc.currentLabels) { - if (mc.currentLabels[l].name == name) return mc.currentLabels[l].frame; - } - return 1; - } - // generate a quick text field of a certain color/style - public static function BasicTextField(color:uint, - size:int, - font:String, - text:String, - additional:Object = null, - align = "left"):TextField - { - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.align = align; - if (additional != null) for (var a in additional) f[a] = additional[a]; - f.font = font; - f.color = color; - f.size = size; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.text = text; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - return t; - } - public static function var_dump(_obj, name = "Dump") - { - _strace(name + " " + (_obj) + " {"); - flash.utils.describeType(_obj); - var varList:XMLList = flash.utils.describeType(_obj)..variable; - - for(var i:int; i < varList.length(); i++) - { - //Show the name and the value - _strace(" " + varList[i].@name+' = '+ _obj[varList[i].@name]); - } - _strace("}"); - } - - public static function SetChildFrames(parentClip, frame, exclude = null) - { - if (parentClip is MovieClip && parentClip.name != exclude) - { - parentClip.gotoAndStop(frame); - for (var i = 0; i < parentClip.numChildren; i++) - { - Utils.SetChildFrames(parentClip.getChildAt(i), frame, exclude); - } - } - } - - public static function SetChildFramesNoParent(parentClip, frame, exclude = null) - { - if (parentClip is MovieClip && parentClip.name != exclude) - { - for (var i = 0; i < parentClip.numChildren; i++) - { - Utils.SetChildFrames(parentClip.getChildAt(i), frame, exclude); - } - } - } - - //modifies the array passed as parameter, following the MO of the built in Array.sort() - public static function insertionSort(array:Array, compareFunction:Function):void - { - for(var i:int=1; i < array.length; i++) - { - var value:Object = array[i]; - var k:int=i-1; - while( k >= 0 && compareFunction(array[k], value) == -1) - { - array[k+1]=array[k]; - k--; - } - array[k+1]=value; - } - } - - - public static function Screenshot(sourceClip, receiverURL, filename) - { - - var jpgSource:BitmapData; - - if (sourceClip is Stage) - { - jpgSource = new BitmapData (sourceClip.stageWidth, sourceClip.stageHeight); - } else { - jpgSource = new BitmapData (sourceClip.width, sourceClip.height); - } - - jpgSource.draw(sourceClip); - - var jpgEncoder:JPGEncoder = new JPGEncoder(85); - var jpgStream:ByteArray = jpgEncoder.encode(jpgSource); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - var jpgURLRequest:URLRequest = new URLRequest(receiverURL+"?name="+filename); - jpgURLRequest.requestHeaders.push(header); - jpgURLRequest.method = URLRequestMethod.POST; - jpgURLRequest.data = jpgStream; - navigateToURL(jpgURLRequest, "_blank"); - - } - - - public static function SetColors(clip, color) - { - var colorTransform:ColorTransform; - - if (clip == null || color == null) return; - - if (clip.hasOwnProperty("outline") && clip.outline != null) - { - colorTransform = clip.outline.transform.colorTransform; - colorTransform.color = color.Outline; - clip.outline.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryOutline") && clip.secondaryOutline != null) - { - colorTransform = clip.secondaryOutline.transform.colorTransform; - colorTransform.color = color.LightOutline; - clip.secondaryOutline.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("color") && clip.color != null) - { - colorTransform = clip.color.transform.colorTransform; - colorTransform.color = color.Primary; - clip.color.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryColor") && clip.secondaryColor != null) - { - colorTransform = clip.secondaryColor.transform.colorTransform; - colorTransform.color = color.Secondary; - clip.secondaryColor.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("shadow") && clip.shadow != null) - { - colorTransform = clip.shadow.transform.colorTransform; - colorTransform.color = color.Shadow; - clip.shadow.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryShadow") && clip.secondaryShadow != null) - { - colorTransform = clip.secondaryShadow.transform.colorTransform; - colorTransform.color = color.SecondaryShadow; - clip.secondaryShadow.transform.colorTransform = colorTransform; - } - } - /* returns a rect with the x, and y pos to center and the scaleX and scaleY as width and height */ - public static function GetUniformScaleRect(clip:MovieClip, maxWidth, maxHeight) - { - var rect:Rectangle = new Rectangle(0,0,0,0); - - var widthScale = Math.min(maxWidth / clip.width, 999); - var heightScale = Math.min(maxHeight / clip.height, 999); - - var scale = 1; - if (widthScale > heightScale) - { - scale = heightScale; - } else { - scale = widthScale; - } - - rect.width = clip.width * scale; - rect.height = clip.height * scale; - - var pb = clip.getBounds(clip); - var xadjust = -pb.left * scale; - var yadjust = -pb.top * scale; - - rect.x = xadjust + (maxWidth - rect.width) / 2; - rect.y = yadjust + (maxHeight - rect.height) / 2; - - rect.width = scale; - rect.height = scale; - - return rect; - } - - public static function Dec2Hex(d) - { - var chars:String = "0123456789ABCDEF"; - var str:String = ""; - while (d > 0 || str.length < 2) - { - var digit = d % 16; - d = (d - digit) / 16; - str = chars.charAt(digit) + str; - } - return str; - } - - public static function Hex2Dec(h:String) - { - var chars:String = "0123456789ABCDEF"; - var val = 1; - var res = 0; - for (var i = h.length - 1; i >= 0; i--) - { - res += chars.indexOf(h.substr(i, 1)) * val; - val *= 16; - } - return res; - } - - public static function ShallowCopyArray(array:Array) - { - if (!array) return null; - - var newArray:Array = []; - for (var i:int = 0; i < array.length; i++) - { - newArray.push(array[i]); - } - return newArray; - } - - /* Note: Will fail if any items in either array have reference type semantics (unless they point to the same object) - * (as opposed to value type semantics) - */ - public static function areEqual(a:Array,b:Array):Boolean { - if(a.length != b.length) { - return false; - } - var len:int = a.length; - for(var i:int = 0; i < len; i++) { - if(a[i] !== b[i]) { - return false; - } - } - return true; - } - - /* Note: Will fail if any items in either array have reference type semantics - * (as opposed to value type semantics) - */ - public static function objectsAreEqual(a:Object,b:Object):Boolean { - - for (var i in a) - { - if (!b.hasOwnProperty(i) || a[i] != b[i]) return false; - } - - return true; - } - - public static function DeepCopyClone (source : Object) : * - { - var array : ByteArray = new ByteArray (); - - array.writeObject (source); - array.position = 0; - - return array.readObject (); - } - - // {a:1, b:2} => [1,2] - public static function ObjectValues (obj:Object):Array { - var array = []; - for (var key in obj) array.push(obj[key]); - return array; - } - - // {a:1, b:2} => ["a","b"] - public static function ObjectKeys (obj:Object):Array { - var array = []; - for (var key in obj) array.push(key); - return array; - } - - // normal random variate generator; mean m, standard deviation s - public static function BoxMullerRandomNormal(m:Number, s:Number) : Number - { - var x1, x2, w, y1:Number; - var y2:Number; - var use_last:Boolean = false; - - if (use_last == true) /* use value from previous call */ - { - y1 = y2; - use_last = false; - } - else - { - do { - x1 = 2.0 * Math.random() - 1.0; - x2 = 2.0 * Math.random() - 1.0; - w = x1 * x1 + x2 * x2; - } while ( w >= 1.0 ); - - w = Math.sqrt( (-2.0 * Math.log( w ) ) / w ); - y1 = x1 * w; - y2 = x2 * w; - use_last = true; - } - - return( m + y1 * s ); - } - - public static function SanitizeNumber(n) - { - if (n is Number) - { - if (n == Number.NEGATIVE_INFINITY || n == Number.POSITIVE_INFINITY || n == Number.NaN) return 0; - } - return n; - } - - public static function IsNumberInvalid(n) - { - if (n is Number) - { - if (n == Number.NEGATIVE_INFINITY || n == Number.POSITIVE_INFINITY || n == Number.NaN) return true; - } - return false; - } - - public static function LimitNumberToMax(n) - { - if (n == Number.POSITIVE_INFINITY) return Number.MAX_VALUE; - return n; - } - - /* - value= Math.round(20/7); - value= int((20/7)*10)/10; - value= int((20/7)*100)/100; - value= int((20/7)*1000)/1000; - value= int((20/7)*10000)/10000; - */ - public static function RoundToDecimalPlaces(number:Number, places:int) - { - return Math.round((number)*Math.pow(10,places))/Math.pow(10,places); - } - - public static function GetShuffledArray(a:Array) : Array - { - var r:Array = a.concat(); - r.sort(randomSort); - return r; - } - - ///Convenience function since I keep forgetting the name of randomSort (hint: it's randomSort) - public static function ShuffleArray(a:Array) - { - a.sort(randomSort); - } - - public static function PickRandom(a:Array) - { - return a[Math.floor(Math.random() * a.length)]; - } - - /** - * Returns n elements of array a, up to a maximum of a's length. - * If forceCopy is set, the returned array will always be a new instance. - */ - public static function PickRandomSet(a:Array, n:int, forceCopy:Boolean=false):Array - { - if (a.length <= n || a.length == 0) - { - if (forceCopy) return a.concat(); - else return a; - } - if (n == 1) return [PickRandom(a)]; - - var shuffled:Array = GetShuffledArray(a); - return shuffled.slice(0, n); - } - - /** - * Does not randomly sort an array! To do that, Use the default array.sort with this as its argument. - * If you want a new, shuffled array, use GetShuffledArray - */ - public static function randomSort(a:*, b:*) : Number - { - if (Math.random() < 0.5) return -1; - else return 1; - } - - /** - * Returns the union of arr1 and arr2. If the elements are not primitive types, you'll need to provide a sorting function. - * If inPlace, a1 and a2 will be sorted. - * If they already contain duplicates, then all bets are off. - */ - public static function MergeArrays(arr1:Array, arr2:Array, sortFunc:Function = null, inPlace:Boolean = false) : Array - { - var ret:Array = []; - var a1:Array = (inPlace) ? arr1 : arr1.slice(); - var a2:Array = (inPlace) ? arr2 : arr2.slice(); - - var len1:uint = a1.length; - var len2:uint = a2.length; - var i1:uint = 0; - var i2:uint = 0; - - //Boring cases - if (len1 == 0 && len2 == 0) return ret; - if (len1 == 0) return (inPlace) ? a2.slice() : a2; - if (len2 == 0) return (inPlace) ? a1.slice() : a1; - - if (sortFunc) - { - a1.sort(sortFunc); - a2.sort(sortFunc); - } - else - { - a1.sort(); - a2.sort(); - } - - while (i1 < len1) - { - //add all from a2 up to a1[i1] - while (i2 < len2 && a2[i2] <= a1[i1]) - { - ret.push(a2[i2]); - i2 += 1; - } - if (ret.length == 0 || a1[i1] != ret[ret.length-1]) ret.push(a1[i1]); - i1 += 1; - } - - while (i2 < len2) ret.push(a2[i2]); - - return ret; - } - - public static function ConvertToHHMMSS(seconds:Number):String - { - var s:Number = seconds % 60; - var m:Number = Math.floor((seconds % 3600 ) / 60); - var h:Number = Math.floor(seconds / (60 * 60)); - - var hourStr:String = (h == 0) ? "" : DoubleDigitFormat(h) + ":"; - var minuteStr:String = DoubleDigitFormat(m) + ":"; - var secondsStr:String = DoubleDigitFormat(s); - - return hourStr + minuteStr + secondsStr; - } - - public static function DoubleDigitFormat(num:uint):String - { - if (num < 10) - { - return ("0" + num); - } - return String(num); - } - - public static function CapitolizeString(str:String) : String - { - var firstChar:String = str.substr(0, 1); - var restOfString:String = str.substr(1, str.length); - - return firstChar.toUpperCase()+restOfString.toLowerCase(); - } - - // ^ Nice spelling, goof! - public static function CapitalizeString(str:String) : String - { - return CapitolizeString(str); - } - - public static function GetListString(listStrings:Array) : String - { - var andString:String = "&"; - var count:int = 0; - - var listString:String = ""; - for (var i = 0; i < listStrings.length; i++) - { - if (count > 0 && listStrings.length == 2) listString += " "+andString+" "; // For just 2 items - else if (count == listStrings.length-1 && listStrings.length > 2) - { - // For adding "and" at the end of 3+ items. It is: ", and $(item)" - var endingString:String = ""; - endingString = endingString.replace("$(item)", listStrings[i]); - listString += endingString; - count++; - continue; - } - else if (count > 0) listString += ", "; // Comma separated list - - listString += listStrings[i]; - count++; - } - - return listString; - } - - /* - * Flash doesn't like the way MySQL prints dates (2016-06-02 13:00:00) - * "The year month and day terms can be separated by a forward slash (/) or by spaces, but never by a dash (-)." - */ - public static function ParseDate (dateString:String) : Date - { - var pattern:RegExp = /-/g; - var date = new Date(); - dateString = dateString.replace(pattern, "/"); - date.setTime(Date.parse(dateString)); - return date; - } - - /* - * For display only, not intended to be read by ParseDate - * Tuesday, June 7th, 2016 at 10:32 AM - */ - public static function FormatDate (date:Date) : String - { - var f:DateTimeFormatter = new DateTimeFormatter("en-US"); - var dateStr:String; - var lastChar:String; - - //Flash can't do "1st", "2nd", etc - - f.setDateTimePattern("d"); - dateStr = f.format(date); - lastChar = dateStr.charAt(dateStr.length - 1); - - if (lastChar == "1" && dateStr != "11") dateStr += "st"; - else if (lastChar == "2" && dateStr != "12") dateStr += "nd"; - else if (lastChar == "3" && dateStr != "13") dateStr += "rd"; - else dateStr += "th"; - - f.setDateTimePattern("EEEE, MMMM '" + dateStr + "', yyyy 'at' h:mm a"); - return f.format(date); - } - - /* Simply counts the number of properties on the object - */ - public static function CountObjectParameters(obj:Object):int - { - var cnt:int=0; - - for (var s:String in obj) cnt++; - - return cnt; - } - - /** - * For when shit gets real - */ - public static function PrintStackTrace() - { - try { - throw new Error('StackTrace'); - } catch (e:Error) { - _strace(e.getStackTrace()); - } - } - } -} \ No newline at end of file diff --git a/org/aszip/compression/CompressionMethod.as b/org/aszip/compression/CompressionMethod.as deleted file mode 100644 index 42fe7a0..0000000 --- a/org/aszip/compression/CompressionMethod.as +++ /dev/null @@ -1,17 +0,0 @@ -package org.aszip.compression - -{ - - /** - * The CompressionMethod class lets you choose the compression algorithms used for the files in the ZIP. - */ - public class CompressionMethod - - { - - public static var GZIP:String = 'GZIP'; - public static var NONE:String = 'NONE'; - - } - -} \ No newline at end of file diff --git a/org/aszip/crc/CRC32.as b/org/aszip/crc/CRC32.as deleted file mode 100644 index fcbc4f0..0000000 --- a/org/aszip/crc/CRC32.as +++ /dev/null @@ -1,63 +0,0 @@ -/** -* AS3 CRC32 algorithm implementation -*/ - -package org.aszip.crc -{ - - import flash.utils.ByteArray; - - public class CRC32 { - - private var crc32:int; - private static var CRCTable:Array = initLookupTable(); - - private static function initLookupTable ():Array - { - - var polynomial:int = 0xEDB88320; - var CRC32Table:Array = new Array(256); - - var i:int = 256; - var j:int = 8; - - while ( i-- ) - - { - - var crc:int = i; - - while ( j-- ) crc = (crc & 1) ? (crc >>> 1) ^ polynomial : (crc >>> 1); - - j = 8; - - CRC32Table [ i ] = crc; - - } - - return CRC32Table; - - } - - public function generateCRC32 ( pBytes:ByteArray ):void - { - - var length:int = pBytes.length; - - var crc:int = ~crc32; - - for ( var i:int = 0; i < length; i++ ) crc = ( crc >>> 8 ) ^ CRCTable[ pBytes[i] ^ (crc & 0xFF) ]; - - crc32 = ~crc; - - } - - public function getCRC32 ():int - { - - return crc32 & 0xFFFFFFFF; - - } - - } -} \ No newline at end of file diff --git a/org/aszip/encoding/PNGEnc.as b/org/aszip/encoding/PNGEnc.as deleted file mode 100644 index 9847cd6..0000000 --- a/org/aszip/encoding/PNGEnc.as +++ /dev/null @@ -1,218 +0,0 @@ -/** -* PNG encoding class from kaourantin.net, optimised by 5etdemi.com/blog -* @author kaourantin -* @version 0.1 -*/ - -package org.aszip.encoding -{ - import flash.utils.ByteArray; - import flash.display.BitmapData; - import flash.utils.getTimer; - import flash.geom.Rectangle; - - public class PNGEnc { - - public static function encode(img:BitmapData, type:uint = 0):ByteArray { - - - - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - if(img.transparent || type == 0) - { - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - } - else - { - IHDR.writeUnsignedInt(0x08020000); //24bit RGB - } - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - - switch(type) - { - case 0: - writeRaw(img, IDAT); - break; - case 1: - writeSub(img, IDAT); - break; - } - - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - - - - return png; - } - - private static function writeRaw(img:BitmapData, IDAT:ByteArray):void - { - var h:int = img.height; - var w:int = img.width; - var transparent:Boolean = img.transparent; - - for(var i:int=0;i < h;i++) { - // no filter - if ( !transparent ) { - var subImage:ByteArray = img.getPixels( - new Rectangle(0, i, w, 1)); - //Here we overwrite the alpha value of the first pixel - //to be the filter 0 flag - subImage[0] = 0; - IDAT.writeBytes(subImage); - //And we add a byte at the end to wrap the alpha values - IDAT.writeByte(0xff); - } else { - IDAT.writeByte(0); - var p:uint; - for(var j:int=0;j < w;j++) { - p = img.getPixel32(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - (p>>>24))); - } - } - } - } - - private static function writeSub(img:BitmapData, IDAT:ByteArray):void - { - var r1:uint; - var g1:uint; - var b1:uint; - var a1:uint; - - var r2:uint; - var g2:uint; - var b2:uint; - var a2:uint; - - var r3:uint; - var g3:uint; - var b3:uint; - var a3:uint; - - var p:uint; - var h:int = img.height; - var w:int = img.width; - - for(var i:int=0;i < h;i++) { - // no filter - IDAT.writeByte(1); - if ( !img.transparent ) { - r1 = 0; - g1 = 0; - b1 = 0; - a1 = 0xff; - for(var j:int=0;j < w;j++) { - p = img.getPixel(j,i); - - r2 = p >> 16 & 0xff; - g2 = p >> 8 & 0xff; - b2 = p & 0xff; - - r3 = (r2 - r1 + 256) & 0xff; - g3 = (g2 - g1 + 256) & 0xff; - b3 = (b2 - b1 + 256) & 0xff; - - IDAT.writeByte(r3); - IDAT.writeByte(g3); - IDAT.writeByte(b3); - - r1 = r2; - g1 = g2; - b1 = b2; - a1 = 0; - } - } else { - r1 = 0; - g1 = 0; - b1 = 0; - a1 = 0; - for(var k:int=0;k < w;k++) { - p = img.getPixel32(k,i); - - a2 = p >> 24 & 0xff; - r2 = p >> 16 & 0xff; - g2 = p >> 8 & 0xff; - b2 = p & 0xff; - - r3 = (r2 - r1 + 256) & 0xff; - g3 = (g2 - g1 + 256) & 0xff; - b3 = (b2 - b1 + 256) & 0xff; - a3 = (a2 - a1 + 256) & 0xff; - - IDAT.writeByte(r3); - IDAT.writeByte(g3); - IDAT.writeByte(b3); - IDAT.writeByte(a3); - - r1 = r2; - g1 = g2; - b1 = b2; - a1 = a2; - } - } - } - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - for (var n:uint = 0; n < 256; n++) { - //var c:uint = n; - for (var k:uint = 0; k < 8; k++) { - if (n & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - var c:uint = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - 0xff] ^ (c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/org/aszip/saving/Download.as b/org/aszip/saving/Download.as deleted file mode 100644 index 52cbb0a..0000000 --- a/org/aszip/saving/Download.as +++ /dev/null @@ -1,14 +0,0 @@ -package org.aszip.saving - -{ - - public class Download - - { - - public static const ATTACHMENT:String = "attachment"; - public static const INLINE:String = "inline"; - - } - -} \ No newline at end of file diff --git a/org/aszip/saving/Method.as b/org/aszip/saving/Method.as deleted file mode 100644 index 208a254..0000000 --- a/org/aszip/saving/Method.as +++ /dev/null @@ -1,14 +0,0 @@ -package org.aszip.saving - -{ - - public class Method - - { - - public static const LOCAL:String = "local"; - public static const REMOTE:String = "remote"; - - } - -} \ No newline at end of file diff --git a/AnimatedSkeletonGenerator.as b/AnimatedSkeletonGenerator.as deleted file mode 100644 index bd560c1..0000000 --- a/AnimatedSkeletonGenerator.as +++ /dev/null @@ -1,649 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - import CharacterExport.Piece; - import CharacterExport.PieceFrameInfo; - import CharacterExport.PieceSequence; - - public class AnimatedSkeletonGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - public function get Def():GraphicExportDef { return def; } - private var callback; - private var sequences:Array; - private var frames:Array; - public function GetFrames():Array - { - return frames; - } - public function GetData() - { - var usedPieces:Array = library.GetAllUsedPieces(); - var pieces:Array = usedPieces.map(function(p:Piece, i, arr) - { - var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; - var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; - return {rect:r, center:c, resource:p.Frame.sheetIndex}; - }); - return { - pieces:pieces, - scale:def.scale, - sequences:sequences.map( - function(s:Sequence, i, arr) - { - return { - length:s.Length, - pieces:s.PieceSequences.map( - function (ps:PieceSequence, i, arr) - { - var frames:Array = new Array(); - for (var i = 0; i < s.Length; i++) - { - var pfi:PieceFrameInfo = ps.GetFrame(i + 1); - var frame = - { - present:pfi.Present, - depth:pfi.Depth - }; - if (pfi.Present) - { - frame.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; - } - frames.push(frame); - } - return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; - } - ) - }; - } - ) - }; - } - public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - private var library:PieceLibrary - public function Go(callback) - { - sequences = new Array(); - library = new PieceLibrary(); - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - var s:Sequence = new Sequence(this, library, i, c); - s.GetAnimation(); - sequences.push(s); - break; - } - } - } - - frames = library.GetAllUsedPieces().map( - function(p:Piece, i, arr) - { - return p.Frame; - } - ); - - callback(true); - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - } -} - -class Sequence -{ - import flash.display.*; - import flash.geom.*; - - private var pieces:Array = new Array(); - private var pieceSequences:Array = new Array(); - public function get PieceSequences():Array { return pieceSequences; } - private var src:MovieClip; - private var seq:int; - private var seqLength:int; - public function get Length():int { return seqLength; } - private var library:PieceLibrary; - private var generator:AnimatedSkeletonGenerator; - - public function Sequence(generator:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) - { - this.generator = generator; - this.library = library; - this.seq = seq; - this.seqLength = src.totalFrames; - this.src = src; - } - - public function GetAnimation() - { - for (var i = 0; i < seqLength; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - RecursePieces(src, i + 1, 0, new Matrix()); - } - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - //_strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = Utils.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - var i; - var m:Matrix; - var useMatrix:Array = []; - for (i = 0; i < clips.length; i++) - { - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = Utils.GetAccurateBounds(clips[i]); - Utils.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - Utils.ScaleRect(bounds, generator.Def.scale); - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (i = 0; i < clips.length; i++) - { - m = useMatrix[i]; - m.scale(generator.Def.scale, generator.Def.scale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1 / generator.Def.scale, 0, 0, 1 / generator.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - var i; - for (i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, seqLength); - piece.AddUse(seq); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= generator.Def.scale; - - var partsA = Utils.Decompose(transformA); - var partsB = Utils.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var i, j, info:PieceFrameInfo, index; - var sequenceByPresent = {}; - for (i in pieceSequences) - { - var str = ""; - for (j = 0; j < length; j++) - { - info = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (i = 0; i < all.length; i++) - { - index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - var p:Piece; - for (i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (j = 0; j < length; j++) - { - info = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (j = 0; j < group.length; j++) - { - p = group[j].GetPiece(); - p.RemoveUse(seq); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - Utils.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - Utils.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, seqLength); - p.AddUse(seq); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (i in groups) - { - if (groups[i].length > 1) - { - for (j in groups[i]) - { - index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(seq) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var i; - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var ps:PieceSequence; - var r:Rectangle = null; - var i; - var mat:Matrix; - for (i in pieceSequences) - { - ps = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - mat = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - Utils.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - Utils.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - //_strace("failed to create bitmap data"); - } - - var depths:Array = []; - for (i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (i = 0; i < sorts.length; i++) - { - ps = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - mat = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } -} \ No newline at end of file diff --git a/AnimatedSpriteGenerator.as b/AnimatedSpriteGenerator.as deleted file mode 100755 index 17585e9..0000000 --- a/AnimatedSpriteGenerator.as +++ /dev/null @@ -1,113 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class AnimatedSpriteGenerator implements IFramesSource - { - private var src:MovieClip; - private var def:GraphicExportDef; - private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] - private var callback; - public function GetFrames():Array - { - var ret:Array = []; - for (var i in sequences) - { - ret = ret.concat(sequences[i].map(function(frame:AnimatedSpriteFrame, i, arr) { return frame.info; })); - } - return ret; - } - - public function GetData() - { - return { - scale:def.scale, - sequences:sequences.map( - function(s:Array, i, sArr) - { - return { - frames: s.map( - function(f:AnimatedSpriteFrame, i, fArr) - { - var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; - var c = {x:f.offset.x, y:f.offset.y}; - return {rect:r, center:c, resource:f.info.sheetIndex}; - } - ) - }; - } - ) - }; - } - - public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) - { - this.src = src; - this.def = def; - } - - public function Go(callback) - { - this.callback = callback; - for (var i = 0; i < src.totalFrames; i++) - { - Utils.WeirdGotoFrame(src, i + 1); - Utils.RecursivelyStop(src); - - for (var j = 0; j < src.numChildren; j++) - { - var c = src.getChildAt(j); - if (c is MovieClip) - { - sequences.push(GetAnimation(c, i)); - break; - } - } - } - - callback(true); - } - - private function GetAnimation(m:MovieClip, seq:int):Array - { - var ret:Array = new Array(); - for (var i = 0; i < m.totalFrames; i++) - { - Utils.WeirdGotoFrame(m, i + 1); - Utils.RecursivelyStop(m); - - var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); - var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); - - var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); - - var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); - b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); - - var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); - - var frame:AnimatedSpriteFrame = new AnimatedSpriteFrame(); - frame.info = info; - frame.sequence = seq; - frame.frame = i; - frame.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); - - ret.push(frame); - } - - return ret; - } - } -} - -class AnimatedSpriteFrame -{ - import flash.display.*; - import flash.geom.*; - - public var info:FrameInfo; - public var sequence:int = 0; - public var frame:int = 0; - public var offset:Point = new Point(); -} \ No newline at end of file diff --git a/CharacterExport/AnimPieceExportBuilder.as b/CharacterExport/AnimPieceExportBuilder.as deleted file mode 100644 index b1eba4b..0000000 --- a/CharacterExport/AnimPieceExportBuilder.as +++ /dev/null @@ -1,161 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.*; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import flash.net.FileReference; - import flash.events.*; - - public class AnimPieceExportBuilder - { - protected var sets:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public static const OUTPUT_VERSION = 3; - - public function AnimPieceExportBuilder(sets:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.sets = sets; - - for (var i in sets) - { - for (var j in sets[i].Pieces) - { - if (sets[i].Pieces[j].IsAnimated) - { - var exporter:CharacterExporter = sets[i].Pieces[j].Exporter; - var usedPieces:Array = exporter.GetAllPieces(); - for (var k in usedPieces) - { - pieces.push(usedPieces[k]); - } - } - else - { - pieces.push(sets[i].Pieces[j]); - } - } - //pieces = pieces.concat(sets[i].Pieces); - } - - sheetWidth = sheetHeight = ExportBuilder.DetermineMinimumSheetSize(pieces); - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes[i] = node; - - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - output.writeUnsignedInt(sets.length); - - for (var i = 0; i < sets.length; i++) - { - output.writeUTF(sets[i].Name); - - - output.writeUnsignedInt(sets[i].Pieces.length); - var setPieces:Array = sets[i].Pieces; - for (var j = 0; j < setPieces.length; j++) - { - var currentPiece:AnimationPiece = setPieces[j]; - - //output.writeUnsignedInt(currentPiece.Index); - output.writeUTF(currentPiece.Key); - - output.writeBoolean(currentPiece.IsAnimated); - if (currentPiece.IsAnimated) - { - ExportBuilder.WriteCharacterExport(output, currentPiece.Exporter, this.pieces, this.pieceNodes, piecePad); - } - else - { - - - var index = pieces.indexOf(currentPiece); - var node:RectangleNode = pieceNodes[index]; - - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(setPieces[j].Offset.x); //pieceSequence.CenterPoint.x); - output.writeInt(setPieces[j].Offset.y); //pieceSequence.CenterPoint.y); - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimSetExportBuilder.as b/CharacterExport/AnimSetExportBuilder.as deleted file mode 100644 index 6856960..0000000 --- a/CharacterExport/AnimSetExportBuilder.as +++ /dev/null @@ -1,69 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - - public class AnimSetExportBuilder - { - protected var animations:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - public static const OUTPUT_VERSION = 2; - - public function AnimSetExportBuilder(animations:Array) - { - output.endian = Endian.LITTLE_ENDIAN; - this.animations = animations; - - output.writeUnsignedInt(OUTPUT_VERSION); - - output.writeUnsignedInt(animations.length); - - for (var i in animations) - { - var seq:CharacterSequence = animations[i]; - output.writeUTF(seq.AvatarName); - output.writeUTF(seq.AnimationName); - - var pieces:Array = seq.Exporter.Library.GetAllUsedPieces(); - - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - - //output.writeUnsignedInt(pieceIndex); - output.writeUTF(piece.Name); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - output.compress(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPiece.as b/CharacterExport/AnimationPiece.as deleted file mode 100644 index cc5d20a..0000000 --- a/CharacterExport/AnimationPiece.as +++ /dev/null @@ -1,54 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import djarts.core.*; - - public class AnimationPiece - { - public var Key:String; - - public var IsAnimated = false; - - // IsAnimated == false - public var Offset:Point; - public var Data:BitmapData; - //public var Node:RectangleNode; - - // IsAnimated == true - public var Exporter:CharacterExporter = null; - public var PieceNodes:Array = new Array(); - - private var loadedCallback; - - public function AnimationPiece(key:String, clip:MovieClip, loadedCallback) - { - Key = key; - this.loadedCallback = loadedCallback; - - if (clip.totalFrames > 1) - { - IsAnimated = true; - - Exporter = new CharacterExporter(null); - Exporter.SingleSequenceClip = true; - Exporter.ProcessFromClip(clip, loadedCallback, null); - } - else - { - IsAnimated = false; - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1, bounds.height), true, 0x0); - bd.draw(clip, new Matrix(1, 0, 0, 1, -bounds.left, -bounds.top)); - Offset = new Point(-bounds.left, -bounds.top); - - Data = bd; - - if (loadedCallback != null) loadedCallback(); - } - } - } -} \ No newline at end of file diff --git a/CharacterExport/AnimationPieceSet.as b/CharacterExport/AnimationPieceSet.as deleted file mode 100644 index 48764f4..0000000 --- a/CharacterExport/AnimationPieceSet.as +++ /dev/null @@ -1,46 +0,0 @@ -package CharacterExport -{ - import flash.display.MovieClip; - import djarts.utils.CountWaiter; - - public class AnimationPieceSet - { - public var Name:String; - public var Pieces:Array = new Array(); - - private var waiter:CountWaiter; - public function LoadClip(clip:MovieClip, doneCallback) - { - waiter = new CountWaiter(function(cw) {if (doneCallback != null) doneCallback();}); - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - var child:MovieClip = c as MovieClip; - var m; - if (m = child.name.match("^piece_(.*)_clip$")) - { - - //var index = Number(m[1]); - var found = false; - for (var j in Pieces) - { - if (Pieces[j].Key == m[1]) - { - found = true; - break; - } - } - if (!found) - { - waiter.Wait(); - Pieces.push(new AnimationPiece(m[1], child, waiter.WaitDone)); - } - } - } - } - waiter.Go(); - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterExporter.as b/CharacterExport/CharacterExporter.as deleted file mode 100644 index d3a2331..0000000 --- a/CharacterExport/CharacterExporter.as +++ /dev/null @@ -1,1337 +0,0 @@ -package CharacterExport -{ - import Defs.*; - import flash.display.*; - import djarts.display.*; - import flash.geom.Rectangle; - import djarts.core.*; - import djarts.utils.CountWaiter; - import flash.geom.Matrix; - import flash.geom.Point; - import HeroUI.HeroSprite; - import flash.utils.ByteArray; - import GraphicExport.*; - import djarts.utils.SimpleTimer; - - import org.aszip.zip.ASZip; - import org.aszip.compression.CompressionMethod; - import org.aszip.saving.Method; - import flash.net.FileReference; - - import com.adobe.images.PNGEncoder; - import flash.utils.getQualifiedClassName; - import flash.net.*; - - import flash.events.*; - - public class CharacterExporter - { - protected var loaded = false; - - // the graphic we are working on - protected var heroDef:HeroDef; - - protected var baseGraphicId; - protected var graphicDef:GraphicDef; - protected var graphicId; - protected var graphic:MovieClip; - protected var graphicClass:Class; - - protected var graphicName:String = ""; - public function set GraphicName(val:String) { graphicName = val;} - public function get GraphicName():String { return (graphicName == "") ? getQualifiedClassName(graphic) : graphicName; } - - protected var characterDef:CharacterDef; - protected var externalAnimationData:ExternalAnimationInfo; - protected var force; - - public function get BaseGraphicId() { return baseGraphicId; } - public function get GraphicId() { return graphicId; } - public function get GraphicClass():Class { return graphicClass; } - - protected var isLocalLibrary = false; - protected var library:PieceLibrary; - public function get Library():PieceLibrary { return library; } - - protected var loadWaiter:CountWaiter; - - public var Upscale = 1.0; - - protected var exportSequences:Array; - protected var fullSequence:Array; - - // formatType - public static const NORMAL = 0; - public static const OLDMONSTER = 1; - - protected var formatType; - protected var holder:MovieClip; - public function CharacterExporter(holder:MovieClip = null) - { - this.holder = holder; - } - - public function GetNewSequence(sequence):MovieClip - { - if (!loaded) return null; - - var className = flash.utils.getQualifiedClassName(graphic); - - if (className == "flash.display::MovieClip") - { - graphic.transform.matrix = new Matrix(); - return GetSequenceClip(graphic, sequence); - } - - if (SingleSequenceClip) - { - graphic.transform.matrix = new Matrix(); - return graphic; - } - - if (characterDef) - { - return new CharacterTypeGraphic(graphicId, characterDef, force, sequence, externalAnimationData); - } - - var base:MovieClip = new (graphicClass)(); - return GetSequenceClip(base, sequence); - } - - public function GetSequenceName(sequence):String - { - var base:MovieClip = new (graphicClass)(); - return CharacterExporter.GetSequenceName(base, sequence); - } - - protected var sequences:Array = []; - public function get Sequences():Array { return sequences; } - - protected var doneCallback; - - public function ProcessFromClip(graphic:MovieClip, callback, library:PieceLibrary = null) - { - this.doneCallback = callback; - Reset(); - - this.baseGraphicId = -1; - this.graphicId = -1; - //this.graphicDef = null; - this.graphic = graphic; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - if (SingleSequenceClip) - { - exportSequences = [1]; - fullSequence = [true]; - } - else - { - //exportSequences = [1]; - //fullSequence = [false]; - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++){ - exportSequences[i] = i+1; - fullSequence[i] = true; - } - } - - loaded = true; - graphicClass = Object(graphic).constructor; - - GenerateSequences(); - } - - var defaultExportType = null; - - public function Process(baseGraphicId, callback, library:PieceLibrary = null, defaultExportType = null, scale = 1) - { - this.baseGraphicId = baseGraphicId; - this.defaultExportType = defaultExportType; - this.Upscale = scale; - - if (!library) - { - isLocalLibrary = true; - library = new PieceLibrary(); - } - this.library = library; - - this.doneCallback = callback; - Reset(); - - this.graphicDef = GameData.Instance().GetGraphicDefByID(baseGraphicId); - - if (graphicDef.ExportParams.hasOwnProperty("from_hero_id")) - { - this.heroDef = GameData.Instance().GetHeroDefByID(graphicDef.ExportParams.from_hero_id); - if (heroDef.UseCharacterGraphics) - { - this.characterDef = heroDef.characterDef; - this.force = characterDef.GenerateForce(); - graphicId = GraphicFactory.Instance().ReverseLookup(characterDef.Body); - } else { - graphicId = heroDef.AnimalGraphicID; - } - } else { - graphicId = baseGraphicId; - } - - - this.loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(graphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - - if (characterDef) - { - for (var i in force) - { - var info = force[i]; - if (info.hasOwnProperty("frame")) - { - var partGraphicId = GraphicFactory.Instance().ReverseLookup(info.frame); - if (partGraphicId > 0) - { - loadWaiter.Wait(); - var g = GraphicFactory.Instance().GetGraphicByID(partGraphicId, null, loadWaiter.WaitDone); - if (GraphicFactory.Instance().LoadedOK(g)) - { - loadWaiter.WaitDone(); - } - } - } - } - } - - this.loadWaiter.Go(); - } - - public function Reset() - { - loaded = false; - - heroDef = null; - graphicDef = null; - graphicId = null; - graphic = null; - graphicClass = null; - characterDef = null; - - sequences.splice(0); - - if (isLocalLibrary) - { - library.Reset(); - } - - this.loadWaiter = new CountWaiter(GraphicsLoaded); - } - - protected function GraphicsLoaded(w:CountWaiter) - { - if (!loaded && w == this.loadWaiter) - { - loaded = true; - - graphic = GraphicFactory.Instance().GetGraphicByID(this.graphicId); - graphicClass = Object(graphic).constructor; - - if (characterDef) - { - externalAnimationData = CacheManager.Instance().GetExternalData(graphic); - } - - GenerateSequences(); - } - } - - protected function GenerateSequences() - { - - var exportType = defaultExportType == null ? "monster" : defaultExportType; - if (graphicDef != null && graphicDef.ExportParams.hasOwnProperty("export_type")) - { - exportType = graphicDef.ExportParams.export_type; - } - switch (exportType) - { - case "character": - exportSequences = [1,4,16]; - fullSequence = [true,false,true]; - break; - case "escort": - exportSequences = [1]; - fullSequence = [true]; - break; - case "monster": - default: - exportSequences = []; - fullSequence = []; - for (var i = 0; i < graphic.totalFrames; i++) - { - exportSequences[i] = i+1; - fullSequence[i] = true; - } - break; - } - - formatType = NORMAL; - if (this.characterDef == null && this.graphic.numChildren > 1 && !this.SingleSequenceClip) - { - var hasSingleLengthClip = true; - var lengthClip = null; - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - if (child.totalFrames > 1) - { - if (lengthClip) - { - hasSingleLengthClip = false; - break; - } else { - lengthClip = child; - } - } - } - } - if (hasSingleLengthClip) - { - formatType = OLDMONSTER; - } - } - - NextSequence(); - } - - var nextX = 50; - var nextY = 200; - var sequenceIndex = 0; - public function NextSequence() - { - var i = sequenceIndex; - sequenceIndex++; - - var sequence:CharacterSequence = new CharacterSequence(this, exportSequences[i] - 1, fullSequence[i], formatType); - - sequence.ProducePieces(); - //sequence.DebugPieces(i * 150); - - sequences.push(sequence); - var includeOriginal = true; - if (holder) - { - /* - if (includeOriginal) - { - if (characterDef != null) - { - var char:CharacterGenerator = new CharacterGenerator(); - char.Generate(characterDef, false, false, 1.0, false); - var clip:CacheByFrame = char.GetData(); - holder.addChild(clip); - clip.gotoAndStop(exportSequences[i]); - clip.Frame.gotoAndPlay(1); - clip.x = nextX; - clip.y = nextY; - } - else - { - var original:CacheByFrame = GraphicFactory.Instance().GetCachedClip(GraphicFactory.Instance().GetGraphicName(graphicId), true); - - holder.addChild(original); - original.gotoAndStop(exportSequences[i]); - original.Frame.gotoAndPlay(1); - - original.x = nextX; - original.y = nextY; - } - } - */ - - - var c:CachedMovieClip = sequence.GetDebugClip(); - holder.addChild(c); - c.gotoAndPlay(1); - c.x = nextX + 75; - c.y = nextY; - - - nextX += includeOriginal ? 150 : 75; - - if (nextX > 2400) - { - nextX = 50; - nextY += 150; - } - - } - - if (sequenceIndex == exportSequences.length) - { - SequencesComplete(); - } else { - var t:SimpleTimer = new SimpleTimer(0.01, function(){ NextSequence(); } ); - } - } - - public function SequencesComplete() - { - var pieces:Array = GetAllPieces(); - if (holder) - { - var startX = 800; - var startY = 100; - var count = 0; - var max = 0; - for (var i in pieces) - { - var p:Piece = pieces[i]; - var b:Bitmap = new Bitmap(p.FullData); - holder.addChild(b); - b.x = startX; - b.y = startY; - startY += b.height + 5; - max = Math.max(max, b.width); - if (count == 20) - { - count = 0; - startX += max + 5; - startY = 100; - max = 0; - } - count++; - } - } - - for (var i in pieces) - { - for (var j in pieces) - { - if (i != j) - { - if (pieces[i].Matches(pieces[j].FullData, null)) - { - _strace("MATCHING PIECES: " + i + " " + j); - } - } - } - } - - if (this.isLocalLibrary) - { - this.library.EnsureAllUsedPiecesHaveNames(); - } - - if (doneCallback) doneCallback(); - } - - public function GetAllPieces():Array - { - return library.GetAllUsedPieces(); - } - - protected var templateCallback; - public function ProduceTemplate(callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - } - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - var templateText = getQualifiedClassName(graphic) + "\n"; - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - piece.CenterPoint.x + " " + - piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "end frame\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete(loader, output);}); - } - - public function ProduceTemplateType2(clipName, excludeNames:Array, sampleAnimationIndices:Array, callback) - { - this.templateCallback = callback; - - var output:ASZip = new ASZip(CompressionMethod.GZIP); - - var templateText = clipName + "\n\n"; - - var allPieces:Array = GetAllPieces(); - for (var i = 0; i < allPieces.length; i++) - { - var imgBytes:ByteArray = PNGEncoder.encode(allPieces[i].FullData); - output.addFile(imgBytes, allPieces[i].Name + ".png"); - - templateText += allPieces[i].Name + " " + allPieces[i].CenterPoint.x + " " + allPieces[i].CenterPoint.y + "\n"; - } - - templateText += "\n"; - - var allPiecesUsed = false; - var frame = 1; - var piecesOutput:Array = []; - - while (!allPiecesUsed) - { - for (var i = 0; i < exportSequences.length; i++) - { - var newPiece = false; - var pieces:Array = sequences[i].PieceSequences - for (var j in pieces) - { - var pieceSeq:PieceSequence = pieces[j]; - var pieceIndex = allPieces.indexOf(pieceSeq.GetPiece()); - if (excludeNames.indexOf(pieceSeq.GetPiece().Name) == -1 && pieceSeq.GetFrame(frame).Present && !piecesOutput[pieceIndex]) - { - newPiece = true; - break; - } - } - if (newPiece) - { - var sortOrder = - pieces = pieces.concat(); - pieces.sort(function(a:PieceSequence,b:PieceSequence) - { - return a.GetFrame(frame).Depth - b.GetFrame(frame).Depth; - } - ); - for (var j = 0; j < pieces.length; j++) - { - var pieceSeq:PieceSequence = pieces[j]; - var piece:Piece = pieceSeq.GetPiece(); - var pieceIndex = allPieces.indexOf(piece); - var pieceFrame:PieceFrameInfo = pieceSeq.GetFrame(frame); - if (pieceFrame.Present && excludeNames.indexOf(piece.Name) == -1) - { - templateText += "piece" + pieceIndex + " " + piece.Name + " " + - //piece.CenterPoint.x + " " + - //piece.CenterPoint.y + " " + - pieceFrame.Transform.a + " " + - pieceFrame.Transform.b + " " + - pieceFrame.Transform.c + " " + - pieceFrame.Transform.d + " " + - pieceFrame.Transform.tx + " " + - pieceFrame.Transform.ty + "\n"; - piecesOutput[pieceIndex] = true; - } - } - - templateText += "\n"; - - var usedCount = 0; - for (var j in piecesOutput) - { - if (piecesOutput[j]) usedCount++; - } - if (usedCount >= allPieces.length - excludeNames.length) allPiecesUsed = true; - } - if (allPiecesUsed) break; - } - frame++; - } - - templateText += "end clip\n"; - - for (var i in sampleAnimationIndices) - { - var index = sampleAnimationIndices[i]; - var seq:CharacterSequence = Sequences[index]; - templateText += "\n" + seq.AnimationName + " " + seq.Length + " " + seq.PieceSequences.length + "\n"; - for (var j = 0; j < seq.PieceSequences.length; j++) - { - var ps:PieceSequence = seq.PieceSequences[j]; - templateText += ps.GetPiece().Name + "\n"; - for (var k = 0; k < seq.Length; k++) - { - var info:PieceFrameInfo = ps.GetFrame(k + 1); - templateText += info.Present ? "1" : "0"; - if (info.Present) - { - templateText += " " + info.Depth + " " + info.Transform.a + " " + info.Transform.b + " " + info.Transform.c + " " + info.Transform.d + " " + info.Transform.tx + " " + info.Transform.ty; - } - templateText += "\n"; - } - } - } - - var b:ByteArray = new ByteArray(); - b.writeUTFBytes(templateText); - output.addFile(b, "template.txt"); - - /* - var loader:URLLoader = new URLLoader(new URLRequest("loadTemplate2.jsfl")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {TemplateLoadComplete2(loader, output, clipName);}); - */ - var loaderBytes:ByteArray = new ByteArray(); - loaderBytes.writeUTFBytes(TEMPLATE2); - output.addFile(loaderBytes, clipName + "_Load.jsfl"); - - OutputProjectZip(output, clipName); - } - - private function TemplateLoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, "loadTemplate.jsfl"); - - loader = new URLLoader(new URLRequest("empty.fla")); - loader.dataFormat = URLLoaderDataFormat.BINARY; - loader.addEventListener(Event.COMPLETE, function(e) {EmptyFLALoadComplete(loader, output);}); - } - - private function TemplateLoadComplete2(loader:URLLoader, output:ASZip, fileName) - { - output.addFile(loader.data, fileName + "_Load.jsfl"); - - OutputProjectZip(output, fileName); - } - - private function EmptyFLALoadComplete(loader:URLLoader, output:ASZip) - { - output.addFile(loader.data, getQualifiedClassName(graphic) + ".fla"); - - OutputProjectZip(output, getQualifiedClassName(graphic)); - } - - private function OutputProjectZip(output:ASZip, fileName) - { - var outputBytes:ByteArray = output.saveZIP(Method.LOCAL); - var fr:FileReference = new FileReference(); - fr.addEventListener(Event.COMPLETE, SaveTemplateComplete); - fr.addEventListener(Event.CANCEL, SaveTemplateComplete); - fr.save(outputBytes, fileName + ".zip"); - } - - protected function SaveTemplateComplete(e:Event) - { - if (templateCallback != null) templateCallback(); - } - - - // ==================== - // Utils - // ==================== - static var maxDepth = 99; - public static function SafeGotoFrame2(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - return; - } - - if (clip.currentFrame == 0) return; - frame = Math.max(1, frame); - - if (clip.currentFrame == frame) return; - - var diff = frame - clip.currentFrame; - - AdvanceChildFrames(clip, diff, 0); - - frame = ((frame - 1) % clip.totalFrames) + 1; - - while (clip.currentFrame != frame) - { - if (frame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - protected static function AdvanceChildFrames(clip:MovieClip, diff, depth) - { - if (depth > maxDepth) return; - - for (var i = 0; i < clip.numChildren; i++) - { - var c = clip.getChildAt(i); - if (c is MovieClip) - { - AdvanceChildFrames(c, diff, depth+1); - } - } - if (clip.currentFrame == 0) return; - var newFrame = clip.currentFrame + diff; - newFrame = ((newFrame - 1) % clip.totalFrames) + 1; - while (clip.currentFrame != newFrame) - { - if (newFrame > clip.currentFrame) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function SafeGotoFrame(clip:MovieClip, frame) - { - if (clip is CharacterTypeGraphic) - { - (clip as CharacterTypeGraphic).SetFrame(frame); - } else { - frame = Math.max(1, Math.min(clip.totalFrames, frame)); - if (frame == clip.currentFrame || clip.currentFrame == 0) return; - - var dir = frame > clip.currentFrame ? 1 : -1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (clip.currentFrame != 0) - { - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - } - - public static function GetChildren(clip:MovieClip):Array - { - if (clip is CharacterTypeGraphic) - { - return (clip as CharacterTypeGraphic).GetGraphicChildren(); - } - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function GetSequenceName(base:MovieClip, sequence):String - { - Utils.RecursivelyStop(base, sequence + 1); - if (base.currentLabel == null) return "UnknownAnimation"; - return base.currentLabel; - } - public var SingleSequenceClip = false; - public static function GetSequenceClip(base:MovieClip, sequence):MovieClip - { - Utils.RecursivelyStop(base, sequence + 1); - - if (base.numChildren == 1 && base.getChildAt(0) is MovieClip) - { - return base.getChildAt(0) as MovieClip; - } - - var ret:MovieClip = new MovieClip(); - while (base.numChildren > 0) - { - ret.addChild(base.getChildAt(0)); - } - return ret; - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - private static function HasAnyNamedChildren(m) - { - if (m is MovieClip) - { - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (c is MovieClip) - { - if (!c.name.match("^instance\\d+$")) return true; - if (HasAnyNamedChildren(c as MovieClip)) return true; - } - } - } - return false; - } - - public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) - { - if (baseClip is CharacterTypeGraphic && baseClip == parentClip) return false; - if (clip is MovieClip && baseClip is CharacterTypeGraphic) - { - var ctg:CharacterTypeGraphic = baseClip as CharacterTypeGraphic; - if (ctg.IsForcedPiece(clip)) return true; - } - - //if (HasAnyNamedChildren(clip)) return false; - - //if (!clip.name.match("^instance\\d+$")) return true; - - if (parentClip.totalFrames != 1) return false; - - //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; - if (clip is MovieClip) - { - var m:MovieClip = clip as MovieClip; - if (m.totalFrames > 1) return false; - - if (!m.name.match("^instance\\d+$")) return false; - - for (var i = 0; i < m.numChildren; i++) - { - var c = m.getChildAt(i); - if (!IsFullPiece(baseClip, m, c)) return false; - } - } - return true; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function MatricesMatch(a:Matrix, b:Matrix) - { - if (Math.abs(a.a - b.a) > 0.001) return false; - if (Math.abs(a.b - b.b) > 0.001) return false; - if (Math.abs(a.c - b.c) > 0.001) return false; - if (Math.abs(a.d - b.d) > 0.001) return false; - if (Math.abs(a.tx - b.tx) > 0.001) return false; - if (Math.abs(a.ty - b.ty) > 0.001) return false; - return true; - } - -/* - * START IMPORT PROGRAM (jsfl) - */ - private static const TEMPLATE2:String = ( 0) - { - var animDesc = lines.shift(); - var parts = animDesc.split(" "); - if (parts.length != 3) break; - var animName = parts[0]; - var animLength = parts[1]; - var animParts = parts[2]; - - lib.addNewItem("movie clip", name + animName); - lib.editItem(name + animName); - - var timeline = doc.getTimeline(); - timeline.layers[0].name = "depth" + 0; - - while (timeline.layerCount < animParts) - { - timeline.addNewLayer("depth" + timeline.layerCount, "normal", false); - } - - var parts = []; - var partFrames = []; - - for (var i = 0; i < animParts; i++) - { - var partName = lines.shift(); - - var clipName = "piece_" + partName + "_clip"; - var clipLoc = clipFolderNotExported + "/" + clipName; - if (exportedNames[clipName]) - { - clipLoc = clipFolder + "/" + clipName; - } - var index = lib.findItemIndex(clipLoc); - var item = lib.items[index]; - - parts.push(item); - - var frames = []; - - for (var k = 0; k < animLength; k++) - { - var frameInfo = lines.shift(); - - var lineParts = frameInfo.split(" "); - var info = {present:lineParts[0] == "1"}; - if (info.present) - { - info.index = i; - info.depth = Number(lineParts[1]); - info.transform = { - a:Number(lineParts[2]), - b:Number(lineParts[3]), - c:Number(lineParts[4]), - d:Number(lineParts[5]), - tx:Number(lineParts[6]), - ty:Number(lineParts[7]), - }; - } - - frames.push(info); - } - - partFrames.push(frames); - } - - var lastOrder = ""; - - for (var i = 0; i < animLength; i++) - { - var order = ""; - - var usedParts = []; - for (var k = 0; k < animParts; k++) - { - if (partFrames[k][i].present) - { - usedParts.push(partFrames[k][i]); - } - } - usedParts.sort(function(a, b) { return a.depth - b.depth; }); - for (var j = 0; j < usedParts.length; j++) - { - order += usedParts[j].index + "|"; - } - - if (order != lastOrder) - { - if (i != 0) - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertBlankKeyframe(i); - } - } - - timeline.currentFrame = i; - - for (var j = 0; j < usedParts.length; j++) - { - timeline.setSelectedLayers(animParts - j - 1, true); - doc.addItem({x:0, y:0}, parts[usedParts[j].index]); - } - - lastOrder = order; - - } - else - { - for (var j = 0; j < animParts; j++) - { - timeline.currentLayer = j; - timeline.insertKeyframe(i); - } - } - - for (var j = 0; j < usedParts.length; j++) - { - if (timeline.layers[animParts - j - 1].frames[i].elements.length == 0) - { - _strace("UHOH" + animParts + " " + i + " " + j + " " + usedParts.length); - } - timeline.layers[animParts - j - 1].frames[i].elements[0].matrix = usedParts[j].transform; - } - - //break; - } - - lines.shift(); - - timeline.currentFrame = 1; - - doc.exitEditMode(); - lib.moveToFolder(sampleAnimationsFolder, name + animName, true); - } - - doc.save(true); - -})(); - - ]]> ).toString(); -/* - * END PROGRAM - */ - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterSequence.as b/CharacterExport/CharacterSequence.as deleted file mode 100644 index dcf8c18..0000000 --- a/CharacterExport/CharacterSequence.as +++ /dev/null @@ -1,640 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import djarts.core.*; - import flash.geom.Rectangle; - import flash.geom.Matrix; - import flash.text.TextField; - import djarts.display.CachedMovieClip; - import flash.geom.Point; - import flash.geom.ColorTransform; - - public class CharacterSequence - { - protected var sequence; - public function get Sequence() { return sequence; } - - protected var length = -1; - public function get Length() { return length; } - - protected var exporter:CharacterExporter; - public function get Exporter():CharacterExporter { return exporter; } - protected var graphic; - - protected var pieces:Array = []; - - protected var pieceSequences:Array = []; - public function get PieceSequences():Array { return pieceSequences; } - - protected var formatType; - - protected var animationName:String; - public function get AnimationName():String { return animationName; } - - public var AvatarName:String = ""; - - public function CharacterSequence(exporter:CharacterExporter, sequence, fullSequence, formatType) - { - this.exporter = exporter; - this.sequence = sequence; - this.formatType = formatType; - - graphic = exporter.GetNewSequence(sequence); - if (formatType == CharacterExporter.NORMAL) - { - length = graphic.totalFrames; - } - if (formatType == CharacterExporter.OLDMONSTER) - { - length = 1; - for (var i = 0; i < graphic.numChildren; i++) - { - var c = graphic.getChildAt(i); - if (c is MovieClip && c.totalFrames > 1) - { - length = c.totalFrames; - break; - } - } - } - length = fullSequence ? length : Math.min(length, 1); - CharacterExporter.SafeGotoFrame2(graphic, 1); - - animationName = exporter.GetSequenceName(sequence); - } - - public function ProducePieces() - { - for (var i = 0; i < length; i++) - { - ProducePiecesFromFrame(i); - } - - /* - // test by hiding all alternate usages of Pieces, to make sure we are tracking frame->frame correctly - var usedPiece = {}; - for (var i = 0; i < pieceSequences.length; i++) - { - var pieceIndex = this.pieces.indexOf(pieceSequences[i].GetPiece()); - if (pieceIndex in usedPiece) - { - pieceSequences.splice(i, 1); - i--; - } else { - usedPiece[pieceIndex] = true; - } - } - */ - - //CombinePieces(); - } - - protected function ProducePiecesFromFrame(frame) - { - if (formatType == CharacterExporter.OLDMONSTER) - { - for (var i = 0; i < graphic.numChildren; i++) - { - var child = graphic.getChildAt(i); - if (child is MovieClip) - { - CharacterExporter.SafeGotoFrame2(child, frame + 1); - } - } - } else { - CharacterExporter.SafeGotoFrame2(graphic, frame + 1); - } - - RecursePieces(graphic, frame + 1, 0, new Matrix()); - } - - protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) - { - - _strace(depth+" "+graphic.name+" frame:"+frame); - - var mat:Matrix = graphic.transform.matrix.clone(); - mat.concat(parentMatrix); - - var currentPieces:Array = []; - - var allChildren:Array = CharacterExporter.GetChildren(graphic); - for (var i = 0; i < allChildren.length; i++) - { - if (!allChildren[i].visible) continue; - if (allChildren[i] is MovieClip) - { - if (CharacterExporter.IsFullPiece(this.graphic, graphic, allChildren[i])) - { - currentPieces.push(allChildren[i]); - } else { - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - currentPieces.splice(0); - - depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); - } - } else { - currentPieces.push(allChildren[i]); - } - } - - depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); - return depth; - } - - protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) - { - if (clips.length > 0) - { - var l = clips.length; - var bounds:Rectangle = null; - - var invertMatrix:Matrix = clips[0].transform.matrix.clone(); - invertMatrix.invert(); - - var useMatrix:Array = []; - for (var i = 0; i < clips.length; i++) - { - var m:Matrix; - if (i == 0) - { - m = new Matrix(); - } else { - m = clips[i].transform.matrix.clone(); - m.concat(invertMatrix); - } - - var r:Rectangle = CacheManager.Instance().GetAccurateBounds(clips[i]); - CharacterExporter.TransformRect(r, m); - if (bounds == null) - { - bounds = r.clone(); - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.top < bounds.top) bounds.top = r.top; - if (r.right > bounds.right) bounds.right = r.right; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - - useMatrix.push(m); - } - - CharacterExporter.ScaleRect(bounds, exporter.Upscale); - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); - - for (var i = 0; i < clips.length; i++) - { - var m:Matrix = useMatrix[i]; - m.scale(exporter.Upscale, exporter.Upscale); - m.translate(-bounds.left, -bounds.top); - var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; - bd.draw(clips[i], m, ct, null, null, true); - } - - var center:Point = new Point(-bounds.left, -bounds.top); - - var piece:Piece = exporter.Library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); - if (piece) - { - var mat:Matrix = new Matrix(1/exporter.Upscale, 0, 0, 1/exporter.Upscale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); - mat.concat(clips[0].transform.matrix); - mat.concat(parentMatrix); - - //mat.a /= exporter.Upscale; - //mat.d /= exporter.Upscale; - - var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); - var info:PieceFrameInfo = pieceSequence.GetFrame(frame); - if (info) - { - info.Present = true; - - info.Transform = mat; - - - - info.Depth = depth; - depth++; - } - } - } - return depth; - } - - protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) - { - if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); - var options:Array = []; - for (var i in pieceSequences) - { - if (pieceSequences[i].GetPiece() == piece) - { - var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); - if (frameInfo && !frameInfo.Present) - { - if (pieceSequences[i].CheckMatches(clip)) - { - return pieceSequences[i]; - } else { - options.push(pieceSequences[i]); - } - } - } - } - - if (options.length == 0) - { - var s:PieceSequence = new PieceSequence(piece, this.length); - piece.AddUse(sequence); - pieceSequences.push(s); - return s; - } - - var scores:Array = []; - for (var i = 0; i < options.length; i++) - { - var score = 0; - if (frame > 1) - { - var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); - if (prevInfo && prevInfo.Present) - { - score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); - } - } - scores.push(score); - } - var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - return options[sorted[0]]; - } - - protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) - { - var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); - deltaPos /= exporter.Upscale; - - var partsA = CharacterExporter.Decompose(transformA); - var partsB = CharacterExporter.Decompose(transformB); - - var rotA = partsA.rot; - var rotB = partsB.rot; - var deltaRot = CharacterExporter.GetAngleDiffAbs(rotA, rotB); - - var deltaScaleX = partsA.sx / partsB.sx; - if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; - var deltaScaleY = partsA.sy / partsB.sy; - if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; - var deltaScale = Math.max(deltaScaleX, deltaScaleY); - - var deltaDepth = Math.abs(depthA - depthB); - - return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; - } - - public function DebugPieces(rowY) - { - var count:Array = []; - - for (var i in pieces) - { - count.push(0); - } - - for (var i in pieceSequences) - { - var p:Piece = pieceSequences[i].GetPiece(); - var index = pieces.indexOf(p); - count[index]++; - } - - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - b.y = rowY; - Globals.Instance().GetStage().addChild(b); - nextX += b.width; - var t:TextField = new TextField(); - t.textColor = 0xFF0000; - t.text = "x" + count[i]; - Globals.Instance().GetStage().addChild(t); - t.x = b.x; - t.y = b.y + b.height; - } - } - - public static var ONLYCOMBINEADJACENT = true; - - protected function CombinePieces() - { - var sequenceByPresent = {}; - for (var i in pieceSequences) - { - var str = ""; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = pieceSequences[i].GetFrame(j + 1); - str += (info && info.Present) ? "1" : "0"; - } - if (!(str in sequenceByPresent)) - { - sequenceByPresent[str] = []; - } - sequenceByPresent[str].push(pieceSequences[i]); - } - - for (var presentStr in sequenceByPresent) - { - var all:Array = sequenceByPresent[presentStr]; - - var firstFrame = ("" + presentStr).indexOf("1") + 1; - - var depths:Array = []; - for (var i = 0; i < all.length; i++) - { - depths.push(all[i].GetFrame(firstFrame).Depth); - } - var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var groups:Array = []; - var lastGroup:Array = null; - for (var i = 0; i < all.length; i++) - { - var index = sorted[i]; - if (ONLYCOMBINEADJACENT) - { - if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) - { - lastGroup.push(all[index]); - } else { - lastGroup = []; - groups.push(lastGroup); - lastGroup.push(all[index]); - } - } else { - var foundGroup = false; - for (var j in groups) - { - if (SequenceMatches(groups[j][0], all[index])) - { - groups[j].push(all[index]); - foundGroup = true; - break; - } - } - if (!foundGroup) - { - var g:Array = []; - g.push(all[index]); - groups.push(g); - } - } - } - } - - for (var i in groups) - { - // recovering the original pieces... - // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) - var group:Array = groups[i]; - if (group.length > 1) - { - var origSeq:PieceSequence = group[0]; - var invert:Matrix; - var firstPresent = null; - for (var j = 0; j < length; j++) - { - var info:PieceFrameInfo = origSeq.GetFrame(j + 1); - if (info && info.Present) - { - firstPresent = j + 1; - invert = info.Transform.clone(); - invert.invert(); - break; - } - } - var bounds:Rectangle = null; - var transforms:Array = []; - for (var j = 0; j < group.length; j++) - { - var p:Piece = group[j].GetPiece(); - p.RemoveUse(sequence); - var m:Matrix = new Matrix(); - if (j > 0) - { - //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); - m.concat(invert); - m.concat(group[j].GetFrame(firstPresent).Transform); - //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); - } - var r:Rectangle = p.FullData.rect.clone(); - CharacterExporter.TransformRect(r, m); - - if (bounds == null) - { - bounds = r; - } else { - if (r.left < bounds.left) bounds.left = r.left; - if (r.right > bounds.right) bounds.right = r.right; - if (r.top < bounds.top) bounds.top = r.top; - if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; - } - transforms.push(m); - } - CharacterExporter.RoundRect(bounds); - var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - for (var j = 0; j < group.length; j++) - { - transforms[j].translate(-bounds.left, -bounds.top); - bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); - } - - var p:Piece = this.exporter.Library.GetPieceFromBitmapData(bd, "CombinedPiece"); - var seq:PieceSequence = new PieceSequence(p, this.length); - p.AddUse(sequence); - seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); - - this.pieceSequences.push(seq); - - this.pieces.push(p); - } - } - - for (var i in groups) - { - if (groups[i].length > 1) - { - for (var j in groups[i]) - { - var index = this.pieceSequences.indexOf(groups[i][j]); - if (index == -1) - { - throw new Error("huh?"); - } else { - pieceSequences.splice(index, 1); - } - } - } - } - - - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].GetUses(sequence) == 0) - { - pieces.splice(i, 1); - i--; - } - } - - } - - protected function SequenceMatches(a:PieceSequence, b:PieceSequence) - { - var relative:Matrix = null; - for (var i = 0; i < length; i++) - { - var infoA:PieceFrameInfo = a.GetFrame(i + 1); - var infoB:PieceFrameInfo = b.GetFrame(i + 1); - if (infoA && infoB && infoA.Present && infoB.Present) - { - var m:Matrix = CharacterExporter.GetTransform(infoA.Transform, infoB.Transform); - if (relative == null) - { - relative = m; - } else { - if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; - //if (!CharacterExporter.MatricesMatch(relative, m)) return false; - } - } - } - return true; - } - - public function ProduceFrame(frame, excludeNames:Array = null):MovieClip - { - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - var m:MovieClip = new MovieClip(); - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - var b:Bitmap = new Bitmap(p.FullData); - - var mat:Matrix = new Matrix(); - mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - //b.smoothing = true; - b.transform.matrix = mat; - - m.addChild(b); - } - } - return m; - } - - public function ProduceFrameBitmapData(frame, excludeNames:Array = null) - { - var r:Rectangle = null; - - for (var i in pieceSequences) - { - var ps:PieceSequence = pieceSequences[i]; - var frameInfo:PieceFrameInfo = ps.GetFrame(frame); - if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var piece:Piece = ps.GetPiece(); - var bounds:Rectangle = piece.FullData.rect; - bounds.x -= piece.CenterPoint.x; - bounds.y -= piece.CenterPoint.y; - var mat:Matrix = frameInfo.Transform.clone(); - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - CharacterExporter.TransformRect(bounds, mat); - - if (r == null) - { - r = bounds; - } else { - if (bounds.left < r.left) r.left = bounds.left; - if (bounds.top < r.top) r.top = bounds.top; - if (bounds.right > r.right) r.right = bounds.right; - if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; - } - - } - } - - if (r == null) { - return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; - } - - CharacterExporter.RoundRect(r); - var bd:BitmapData; - try { - bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); - } catch (e){ - _strace("failed to create bitmap data"); - } - - - var depths:Array = []; - for (var i = 0; i < pieceSequences.length; i++) - { - depths.push(pieceSequences[i].GetFrame(frame).Depth); - } - - var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); - - for (var i = 0; i < sorts.length; i++) - { - var ps:PieceSequence = pieceSequences[sorts[i]]; - var info:PieceFrameInfo = ps.GetFrame(frame); - if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) - { - var p:Piece = ps.GetPiece(); - - var mat:Matrix = new Matrix(); - mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); - mat.concat(info.Transform); - - //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); - - mat.translate(-r.left, -r.top); - - bd.draw(p.FullData, mat, null, null, null, true); - } - } - return {data:bd,center_point:new Point(-r.left, -r.top)}; - } - - public function GetDebugClip(excludeNames:Array = null):CachedMovieClip - { - var c:CachedMovieClip = new CachedMovieClip(); - c.frames = []; - for (var i = 0; i < this.length; i++) - { - var frame = this.ProduceFrameBitmapData(i + 1, excludeNames); - c.frames.push(frame.data); - c.framePositions.push(new Point(-frame.center_point.x, -frame.center_point.y)); - } - c.SetTotalFrames(this.length); - return c; - } - } -} \ No newline at end of file diff --git a/CharacterExport/CharacterTypeGraphic.as b/CharacterExport/CharacterTypeGraphic.as deleted file mode 100644 index b619fca..0000000 --- a/CharacterExport/CharacterTypeGraphic.as +++ /dev/null @@ -1,431 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import Defs.CharacterDef; - import djarts.core.*; - import djarts.display.*; - import flash.geom.*; - import flash.utils.*; - - public class CharacterTypeGraphic extends MovieClip - { - protected var graphicId; - protected var characterDef:CharacterDef; - protected var force; - protected var sequence; - - protected var sequenceLabel; - - protected var graphic:MovieClip; - - protected var length; - public override function get totalFrames():int - { - return length; - } - - protected var externalAnimationData:ExternalAnimationInfo; - - public function CharacterTypeGraphic(graphicId, characterDef:CharacterDef, force, sequence, externalAnimationData:ExternalAnimationInfo) - { - this.graphicId = graphicId; - this.characterDef = characterDef; - this.force = force; - this.sequence = sequence; - this.externalAnimationData = externalAnimationData; - - this.graphic = GraphicFactory.Instance().GetGraphicByID(graphicId); - - if (externalAnimationData) - { - PrepareAnimationPieces(); - } - - addChild(graphic); - } - - public function GetGraphicChildren():Array - { - var ret:Array = []; - for (var i = 0; i < graphic.numChildren; i++) - { - ret.push(graphic.getChildAt(i)); - } - return ret; - } - - protected var lastFrameSetPieces:Dictionary = new Dictionary(); - public function IsForcedPiece(clip:DisplayObject) - { - return (clip in lastFrameSetPieces); - } - - public function SetFrame(frame) - { - - frame = Math.max(1, Math.min(length, frame)); - if (externalAnimationData) - { - CacheManager.Instance().ProcessAnimationData(graphic, sequence, frame, this.externalAnimationData, false, force); - } else { - lastFrameSetPieces = new Dictionary(); - makeAllChildrenGoToFrame(graphic, frame, null, graphic, force); - } - } - - public function PrepareAnimationPieces() - { - if (externalAnimationData.UsingSingleSequence) - { - for (var i = 0; i < graphic.numChildren; i++) - { - graphic.getChildAt(i).visible = false; - } - for (var i in externalAnimationData.Data[sequence]) - { - graphic[externalAnimationData.PieceName(sequence, i)].visible = true; - } - } else { - Utils.RecursivelyStop(graphic, sequence + 1); - } - - sequenceLabel = graphic.currentFrameLabel; - if (externalAnimationData.UsingSingleSequence) sequenceLabel = externalAnimationData.SeqNames[sequence]; - - for (var i in externalAnimationData.Data[sequence]) - { - var subclip = graphic[externalAnimationData.PieceName(sequence, i)]; - if (subclip) - { - var clipName = null; - for (var j = 0; j < externalAnimationData.Data[sequence][i].name.length; j++) - { - if (externalAnimationData.Data[sequence][i].name[j] != "") - { - clipName = externalAnimationData.Data[sequence][i].name[j]; - break; - } - } - var checked = false; - if (clipName != null) - { - checked = this.CheckClipName(subclip, clipName, force, graphic, null, sequence + 1, sequenceLabel); - } - if (subclip is MovieClip && subclip.visible && !checked) - { - this.makeAllChildrenGoToFrame(subclip, sequence + 1, null, graphic, force, sequenceLabel); - } - } - } - this.length = externalAnimationData.Data[sequence][0].present.length; - } - - protected function CheckClipName(mc:MovieClip, clipName, force, rootClip, mat:Matrix, frame, rootLabel, keepGoing = true) - { - var nextExceptClip = null; - if (clipName == null) clipName = mc.name; - if (force != null && force[clipName] && force[clipName].hasOwnProperty("color")) { - var ct:ColorTransform = mc.transform.colorTransform; - ct.color = force[clipName].color; - mc.transform.colorTransform = ct; - } - if (force != null && force[clipName] && force[clipName].hasOwnProperty("frame")) { - - this.lastFrameSetPieces[mc] = true; - - var cForce = force[clipName]; - var cFrame = cForce.frame; - - - var totalTransform:Matrix = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - - if (cFrame is String) - { - var l = FindLabel(mc, cFrame); - if (l == -1) - { - var additional = null; //NoFrameCallback(mc, force[clipName],rootLabel); - - // def = cForce - // rootLabel = lowerLabel - var lowerLabel = rootLabel.toLowerCase(); - try { - mc.gotoAndStop(cForce.blank); - Utils.RecursivelyStop(mc, cForce.blank); - } catch (e:Error) - { - } - - if (cFrame != "Default") - { - var additional = GraphicFactory.Instance().GetGraphic(cFrame); - if (!GraphicFactory.Instance().LoadedOK(additional)) - { - // problem! this should have been loaded already... - additional = null; - throw new Error("Tried a custom clip that wasn't already loaded!"); - } else { - additional = FixClip(additional, cForce, lowerLabel); - - additional.name = "wrap_clip_no_play_" + additional.currentFrame; - force["wrap_clip_no_play_" + additional.currentFrame] = {frame:additional.currentFrame, keep_going:false}; - } - } - - if (additional) - { - - var belowChildren:Array; - var aboveChildren:Array; - if (force.search_for_subreplacing && clipName in force.search_for_subreplacing) - { - var testField = "__copy_clips_for_" + clipName + "__"; - if (testField in mc) - { - belowChildren = mc[testField].below; - aboveChildren = mc[testField].above; - } else { - for (var f = 1; f <= mc.totalFrames; f++) - { - Utils.RecursivelyStop(mc, f); - if (mc.currentFrameLabel != cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!belowChildren) belowChildren = []; - belowChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - if (i < mc.numChildren) - { - for (var i = mc.numChildren - 1; i >= 0; i--) - { - var child = mc.getChildAt(i); - if (child is MovieClip) - { - var childName = child.name; - if (child.name in force) - { - if (!aboveChildren) aboveChildren = [];; - aboveChildren.push({name:child.name, - transform:child.transform, - tag:"__only_frame_label_" + force[child.name].blank}); - } - } else { - break; - } - } - } - break; - } - } - mc[testField] = {above:aboveChildren, below:belowChildren}; - } - } - - if (cForce.blank) - { - try { - mc.gotoAndStop(cForce.blank); - } catch (e:Error) {} - if (mc.currentFrameLabel == cForce.blank) - { - for (var i = 0; i < mc.numChildren; i++) - { - var child = mc.getChildAt(i); - if (child is MovieClip && child.name in cForce) - { - // leave it! - } else { - mc.removeChildAt(i); - i--; - } - } - } - } - - var prevChild = mc.getChildByName(additional.name); - if (prevChild) - { - mc.removeChild(prevChild); - } - - if (belowChildren) - { - var tmp = additional; - additional = new MovieClip(); - - for (var i = 0; i < belowChildren.length; i++) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = belowChildren[i].name; - newClip.transform = belowChildren[i].transform; - newClip[belowChildren[i].tag] = true; - additional.addChild(newClip); - } - additional.addChild(tmp); - additional[tmp.name] = tmp; - nextExceptClip = tmp; - } else { - mc[additional.name] = additional; - nextExceptClip = additional; - } - if (aboveChildren) - { - for (var i = aboveChildren.length - 1; i >= 0; i--) - { - var newClip:MovieClip = new MovieClip(); - newClip.name = aboveChildren[i].name; - newClip.transform = aboveChildren[i].transform; - newClip[aboveChildren[i].tag] = true; - additional.addChild(newClip); - } - } - - mc.addChild(additional); - - if (force[clipName].keep_going) - { - makeAllChildrenGoToFrame(additional, frame, totalTransform, rootClip, force, rootLabel, nextExceptClip); - } - nextExceptClip = additional; - } else { - Utils.RecursivelyStop(mc, 1); - } - } else { - if (l != -1) mc.gotoAndStop(l); - } - - } else { - mc.gotoAndStop(force[clipName].frame); - - } - - - - if (force[clipName].keep_going && keepGoing) - { - makeAllChildrenGoToFrame(mc, frame, totalTransform, rootClip, force, "", nextExceptClip); - } - return true; - } - return false; - } - - /* m: clip to set all children to a certain frame - * f: frame to set the children to - * mat: the current total transform to reach this point in the hierarchy - * force: same as above - */ - private function makeAllChildrenGoToFrame(m:MovieClip, f:int, mat:Matrix, rootClip, force = null, rootLabel = "", exceptClip = null):void - { - - for (var i:int = 0; i < m.numChildren; i++) { - var c:* = m.getChildAt(i); - if (c is MovieClip && c != exceptClip) { - var mc:MovieClip = c as MovieClip; - - // the total transformation applied to this clip from all parent transforms - var totalTransform:Matrix; - - if (!CheckClipName(mc, null, force, rootClip, mat, f, rootLabel)) - { - // this clip wasn't specified as being on any particular frame - if (!c.frameAdded) c.frameAdded = f; - - c.gotoAndStop(((f - c.frameAdded) % c.totalFrames) + 1); - totalTransform = mc.transform.matrix.clone(); - if (mat) totalTransform.concat(mat); - makeAllChildrenGoToFrame(c, f, totalTransform, rootClip, force, rootLabel); - - // we upscale the clip before rendering just in case - // the clip has been scaled up (we don't want to lose resolution) - var upscale = 2.0; - - if (mc.name.indexOf("SEPARATE") != -1) { - throw new Error("SEPARATE not supported!"); - /* - var n = mc.name; - var localTransform = new Matrix(1.0 / upscale, 0, 0, 1.0 / upscale); - localTransform.concat(totalTransform); - if (!cacheSeparate.hasOwnProperty(n)) { - if (mc.name.indexOf("BYFRAME") != -1) - { - cacheSeparate[n] = new CacheByFrame(); - cacheSeparate[n].buildCacheFromClip(mc, -1, null, new Matrix(upscale, 0, 0, upscale)); - } else { - cacheSeparate[n] = new CachedMovieClip(); - cacheSeparate[n].buildCacheFromClip(mc, -1, true, null, new Matrix(upscale, 0, 0, upscale)); - } - // render this clip as if it has not been transformed - - - cacheSeparate[n].gotoAndPlay(1); - positionData[n] = []; - - cacheSeparate[n].name = n; - addChild(cacheSeparate[n]); - - - if (n.indexOf("BACK") != -1) { - setChildIndex(cacheSeparate[n], 0); - } - - cacheSeparate[n].transform.matrix = localTransform; - this[n] = cacheSeparate[n]; - this.setPropertyIsEnumerable(n, true); - } - positionData[n][currentFrame] = localTransform; - mc.visible = false; - */ - } - } - } - } - } - - protected function FindLabel(mc:MovieClip, name) - { - var l:Array = mc.currentLabels; - for (var i in l) - { - if (l[i].name == name) return l[i].frame; - } - if (("__only_frame_label_" + name) in mc) - { - return 1; - } - return -1; - } - - protected function FixClip(mc, def, rootLabel) - { - if (rootLabel.indexOf("right") != -1 || rootLabel.indexOf("left") != -1) - { - mc.gotoAndStop(1); - } - if (rootLabel.indexOf("back") != -1) - { - mc.gotoAndStop(2); - } - if (rootLabel.indexOf("front") != -1) - { - mc.gotoAndStop(3); - } - return mc; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/ExportBuilder.as b/CharacterExport/ExportBuilder.as deleted file mode 100644 index 6ae8c82..0000000 --- a/CharacterExport/ExportBuilder.as +++ /dev/null @@ -1,305 +0,0 @@ -package CharacterExport -{ - import flash.utils.*; - import GraphicExport.*; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.Sprite; - import djarts.core.*; - import com.adobe.serialization.json.JSON; - - public class ExportBuilder - { - protected var characters:Array; - protected var output:ByteArray = new ByteArray(); - public function get Output():ByteArray { return output; } - - protected var sheets:Array = []; - - protected var sheetWidth, sheetHeight; - - protected var pieces:Array = []; - protected var pieceNodes:Array = []; - - public var jsonPngSet:JSONPNGSet = new JSONPNGSet(); - public function GetJSONPNGSet(){ return jsonPngSet; } - public var PNGSheets:Array = []; - - public function ExportBuilder(characters:Array, sheetWidth = -1, sheetHeight = -1, library:PieceLibrary = null) - { - output.endian = Endian.LITTLE_ENDIAN; - this.characters = characters; - - if (library) - { - pieces = pieces.concat(library.GetAllUsedPieces()); - } else { - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - - var p:Array = char.GetAllPieces(); - pieces = pieces.concat(p); - } - } - - if (sheetWidth == -1) - { - sheetWidth = sheetHeight = DetermineMinimumSheetSize(pieces); - } - - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - - var piecePad = 2; - - for (var i = 0; i < pieces.length; i++) - { - var piece:Piece = pieces[i]; - var bd:BitmapData = piece.FullData; - var usedNewSheet = false; - for (var sheetIndex = 0; sheetIndex < sheets.length; sheetIndex++) - { - var sheet:SpriteSheet = sheets[sheetIndex]; - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node) - { - pieceNodes.push(node); - sheet.GetBitmap().copyPixels(bd, bd.rect, new Point(node.Rect.x + piecePad, node.Rect.y + piecePad)); - break; - } - } - if (sheetIndex == sheets.length - 1) - { - if (usedNewSheet) - { - throw new Error("This piece is probably too big!"); - } else { - usedNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - sheets.push(newSheet); - } - } - } - } - - output.writeUnsignedInt(sheetWidth); - output.writeUnsignedInt(sheetHeight); - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var png:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - PNGSheets.push(png); - } - - output.writeUnsignedInt(characters.length); - - var jsonOutputObj = {}; - jsonOutputObj.characters = []; - var outputName = ""; - for (var i = 0; i < characters.length; i++) - { - var char:CharacterExporter = characters[i]; - var name = ""; - if (char.BaseGraphicId != -1) - { - name = GameData.Instance().GetGraphicDefByID(char.BaseGraphicId).Name; - } else { - name = char.GraphicName; - } - - output.writeUTF(name); - - WriteCharacterExport(output, char, this.pieces, this.pieceNodes, piecePad); - - var jsonCharacterData = WriteCharacterExportJSON(char, this.pieces, this.pieceNodes, piecePad); - jsonCharacterData.name = name; - outputName = name; - jsonOutputObj.characters.push(jsonCharacterData); - } - output.compress(); - jsonOutputObj.format = "skeletal"; - jsonPngSet.SetData(outputName, jsonOutputObj, PNGSheets); - } - - public static function WriteCharacterExport(output:ByteArray, char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var sequences:Array = char.Sequences; - output.writeUnsignedInt(sequences.length); - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - output.writeUnsignedInt(ps.length); - for (var k = 0; k < ps.length; k++) - { - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - output.writeUnsignedInt(node.Host.HostTexture.SheetIndex); - output.writeUnsignedInt(node.Rect.left + piecePad); - output.writeUnsignedInt(node.Rect.top + piecePad); - output.writeUnsignedInt(node.Rect.width - piecePad * 2); - output.writeUnsignedInt(node.Rect.height - piecePad * 2); - - output.writeInt(piece.CenterPoint.x); - output.writeInt(piece.CenterPoint.y); - - for (var l = 0; l < seq.Length; l++) - { - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - output.writeBoolean(true); - output.writeInt(info.Depth); - var decompose = CharacterExporter.Decompose(info.Transform); - output.writeDouble(decompose.rot); - output.writeDouble(decompose.sx); - output.writeDouble(decompose.sy); - output.writeDouble(info.Transform.tx); - output.writeDouble(info.Transform.ty); - } else { - output.writeBoolean(false); - } - } - } - } - } - - public static function WriteCharacterExportJSON(char:CharacterExporter, pieces:Array, pieceNodes:Array, piecePad) - { - var jsonData = {}; - var sequences:Array = char.Sequences; - jsonData.sequences = []; - for (var j = 0; j < sequences.length; j++) - { - var seq:CharacterSequence = sequences[j]; - //output.writeUnsignedInt(seq.Length); - - var ps:Array = seq.PieceSequences; - var outputPieceSequences = []; - for (var k = 0; k < ps.length; k++) - { - var outputPiece = {}; - - var pieceSequence:PieceSequence = ps[k]; - var piece:Piece = pieceSequence.GetPiece(); - var pieceIndex = pieces.indexOf(piece); - var node:RectangleNode = pieceNodes[pieceIndex]; - - outputPiece.texture_index = node.Host.HostTexture.SheetIndex; - outputPiece.x = node.Rect.left + piecePad; - outputPiece.y = node.Rect.top + piecePad; - outputPiece.w = node.Rect.width - piecePad * 2; - outputPiece.h = node.Rect.height - piecePad * 2; - - outputPiece.cx = piece.CenterPoint.x; - outputPiece.cy = piece.CenterPoint.y; - - outputPiece.n = piece.Name; - - var outputSeq = []; - for (var l = 0; l < seq.Length; l++) - { - var outputFrameInfo = {}; - var info:PieceFrameInfo = pieceSequence.GetFrame(l + 1); - if (info && info.Present) - { - var decompose = CharacterExporter.Decompose(info.Transform); - outputFrameInfo.used = true; - outputFrameInfo.z = info.Depth; - outputFrameInfo.rot = RoundedOutput(decompose.rot); - outputFrameInfo.sx = RoundedOutput(decompose.sx); - outputFrameInfo.sy = RoundedOutput(decompose.sy); - outputFrameInfo.tx = RoundedOutput(info.Transform.tx); - outputFrameInfo.ty = RoundedOutput(info.Transform.ty); - } else { - outputFrameInfo.used = false; - } - outputSeq.push(outputFrameInfo); - } - - outputPiece.sequence = outputSeq; - outputPieceSequences.push(outputPiece); - } - jsonData.sequences.push(outputPieceSequences); - } - - return jsonData; - } - - public static function RoundedOutput(value) - { - var str = ""+value; - var split = str.split("."); - if (split.length == 2) - { - var decPart = split[1]; - if (decPart.length > 3){ - decPart = decPart.substr(0,3); - } - str = split[0] +"."+decPart; - } - return str; - } - - - public static function DetermineMinimumSheetSize(pieces:Array) - { - var sizeFound = false; - var power = 6; - var sheetSize = Math.pow(2, power); - while(!sizeFound) - { - var piecePad = 2; - var sheet:SpriteSheet = new SpriteSheet(sheetSize, sheetSize); - sizeFound = true; - for (var i = 0; i < pieces.length; i++) - { - var piece = pieces[i]; - var bd:BitmapData; - if (piece is AnimationPiece) - { - bd = piece.Data; - } - if (piece is Piece) - { - bd = piece.FullData; - } - if (!sheet.sheetFull) - { - var node:RectangleNode = sheet.GetAllocator().Insert(bd.width + piecePad * 2, bd.height + piecePad * 2); - if (node == null) - { - sizeFound = false; - break; - } - } - } - - //double the size and try again! - if (sizeFound == false) - { - power++; - sheetSize = Math.pow(2, power); - //Max size 1024; - if (sheetSize == 1024) break; - } - - } - - return sheetSize; - } - - } -} \ No newline at end of file diff --git a/CharacterExport/JSONPNGSetSaver.as b/CharacterExport/JSONPNGSetSaver.as deleted file mode 100644 index 483c489..0000000 --- a/CharacterExport/JSONPNGSetSaver.as +++ /dev/null @@ -1,45 +0,0 @@ -package CharacterExport -{ - - import flash.net.FileReference; - import flash.events.*; - - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(json, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+((sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/CharacterExport/Piece.as b/CharacterExport/Piece.as deleted file mode 100644 index 98584f0..0000000 --- a/CharacterExport/Piece.as +++ /dev/null @@ -1,172 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - import djarts.core.*; - - public class Piece - { - protected var size:Point; - protected var fullData:BitmapData; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return fullData; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - CharacterExporter.TransformRect(bounds, m); - CharacterExporter.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - fullData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - fullData = bd; - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - CharacterExporter.ScaleRect(quickBounds, scale); - CharacterExporter.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/CharacterExport/PieceFrameInfo.as b/CharacterExport/PieceFrameInfo.as deleted file mode 100644 index 24662fa..0000000 --- a/CharacterExport/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package CharacterExport -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/CharacterExport/PieceSequence.as b/CharacterExport/PieceSequence.as deleted file mode 100644 index 400aca0..0000000 --- a/CharacterExport/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package CharacterExport -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/ChunkedGraphic.as b/ChunkedGraphic.as deleted file mode 100644 index 234a3b3..0000000 --- a/ChunkedGraphic.as +++ /dev/null @@ -1,60 +0,0 @@ -package { - import flash.display.MovieClip; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import djarts.core.CacheManager; - - public class ChunkedGraphic extends MovieClip - { - - public function ChunkedGraphic(clip:MovieClip, chunkSize:int = 512) - { - this.name = clip.name; - var r:Rectangle = clip.getBounds(clip); - //assuming for very large graphics that the bounds will work... - if (r.width < 2048) r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var rect = new Rectangle(0,0,chunkSize, chunkSize); - var xChunks = Math.ceil(clip.width / chunkSize); - var yChunks = Math.ceil(clip.height / chunkSize); - - var finalChunkWidth = clip.width - chunkSize * Math.floor(clip.width / chunkSize); - var finalChunkHeight = clip.height - chunkSize * Math.floor(clip.height / chunkSize); - - if (finalChunkWidth == 0) finalChunkWidth = chunkSize; - if (finalChunkHeight == 0) finalChunkHeight = chunkSize; - - for (var y = 0; y < yChunks; y++) - { - for (var x = 0; x < xChunks; x++) - { - - var chunkWidth = chunkSize; - var chunkHeight = chunkSize; - if (y == yChunks - 1) chunkHeight = finalChunkHeight; - if (x == xChunks - 1) chunkWidth = finalChunkWidth; - - var chunk:MovieClip = new MovieClip(); - var trans:Matrix = new Matrix(); - trans.tx = -x * chunkSize - r.left; - trans.ty = -y * chunkSize - r.top; - var chunkBitmapData:BitmapData = new BitmapData(chunkWidth, chunkHeight, true, 0); - var chunkBitmap:Bitmap = new Bitmap(chunkBitmapData); - chunkBitmapData.draw(clip, trans); - chunk.addChild(chunkBitmap); - chunk.x = -trans.tx; - chunk.y = -trans.ty; - this.addChild(chunk); - } - } - - this.x = clip.x; - this.y = clip.y; - - } - - } - -} diff --git a/DJArtsLib.swc b/DJArtsLib.swc deleted file mode 100644 index dd5793e..0000000 --- a/DJArtsLib.swc +++ /dev/null Binary files differ diff --git a/DebugExporter-app.xml b/DebugExporter-app.xml deleted file mode 100755 index e2ff06e..0000000 --- a/DebugExporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - DebugExporter - 1.0 - DebugExporter - - DebugExporter - - - DebugExporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/DebugExporter.fla b/DebugExporter.fla deleted file mode 100755 index 9f0dff6..0000000 --- a/DebugExporter.fla +++ /dev/null Binary files differ diff --git a/DebugExporter.swf b/DebugExporter.swf deleted file mode 100755 index 9a1be6e..0000000 --- a/DebugExporter.swf +++ /dev/null Binary files differ diff --git a/Defs/GraphicDef.as b/Defs/GraphicDef.as deleted file mode 100644 index af13908..0000000 --- a/Defs/GraphicDef.as +++ /dev/null @@ -1,65 +0,0 @@ -package Defs -{ - import flash.utils.getTimer; - import flash.utils.getQualifiedClassName; - import com.hurlant.util.der.ObjectIdentifier; - - import djarts.utils.SimpleTimer; - - public class GraphicDef - { - public var ID:int; - public var Name:String = ""; - public var Folder:String = ""; - public var Version:int = 0; - public var FileSize:int = 0; - public var Type:int = 0; - - public var ExportParams:Object = {}; - - public static const EXPORT_FORMAT_NONE = 0; - public static const EXPORT_FORMAT_SPRITESHEET = 1; - public static const EXPORT_FORMAT_CACHEDCLIP = 2; - public static const EXPORT_FORMAT_SKELANIM = 3; - public static const EXPORT_FORMAT_ANIMSETS = 4; - public static const EXPORT_FORMAT_ANIMPIECES = 5; - public static const EXPORT_FORMAT_SCENE = 6; - - // ============ Init ============ // - - public function GraphicDef(data=null) - { - if(data != null) ReadFromData(data); - } - - public function ReadFromData(data) - { - - if (data.hasOwnProperty("id")) ID = data['id']; - if (data.hasOwnProperty("graphic_id")) Name = data['graphic_id']; - if (data.hasOwnProperty("v")) Version = data['v']; - if (data.hasOwnProperty("fs")) FileSize = data['fs']; - if (data.hasOwnProperty("type")) Type = data['type']; - - if (data.hasOwnProperty("graphic")) - { - var graphic:String = data["graphic"]; - var index = graphic.lastIndexOf("/"); - if (index != -1) - { - Folder = graphic.substr(0, index+1); - Name = graphic.substr(index+1); - } - else - { - Name = graphic; - } - } - - if (data.hasOwnProperty("export_params")) ExportParams = data['export_params']; - - } - - - } -} \ No newline at end of file diff --git a/Dialogs.swc b/Dialogs.swc deleted file mode 100644 index afb906c..0000000 --- a/Dialogs.swc +++ /dev/null Binary files differ diff --git a/Exporter-app.xml b/Exporter-app.xml deleted file mode 100755 index 7deb7c5..0000000 --- a/Exporter-app.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - Exporter - 1.0 - Exporter - - Exporter - - - Exporter.swf - standard - false - true - false - portrait - auto - - - false - false - diff --git a/Exporter.as b/Exporter.as deleted file mode 100644 index 0b29136..0000000 --- a/Exporter.as +++ /dev/null @@ -1,308 +0,0 @@ -package -{ - import flash.display.*; - import flash.net.*; - import flash.events.*; - import flash.desktop.*; - import flash.errors.*; - import flash.system.*; - import flash.utils.*; - import by.blooddy.crypto.*; - - public class Exporter extends MovieClip - { - public static var Instance:Exporter = null; - - public static var DefaultPort:int = 7890; - private var driver:Socket = null; - private var debug:Boolean = false; - public function Exporter() - { - Instance = this; - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectDriver(DefaultPort); // try default port - } - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectDriver(parseInt(e.arguments[0])); - } - else - { - ConnectDriver(DefaultPort); - } - } - - private var connected:Boolean = false; - private var lastPort:int; - private function ConnectDriver(port:int, firstTime:Boolean = true) - { - this.lastPort = port; - if (firstTime) - { - Trace("Attempting to connect to driver"); - } - try - { - var s:Socket = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); - s.addEventListener(Event.CONNECT, DriverConnected); - s.addEventListener(Event.CLOSE, DriverClosed); - s.connect("localhost", port); - } - catch (e) - { - Trace("Error establishing wrapper connection"); - } - } - - private function DriverClosed(e) - { - connected = false; - if (debug) - { - ConnectDriver(lastPort); - } - else - { - Quit(); - } - } - - private function DriverError(e) - { - if (!debug) - { - Trace(" Failed to connect"); - } - if (debug && !connected) - { - setTimeout(ConnectDriver, 500, lastPort, false); - } - } - - private function DriverConnected(e) - { - connected = true; - Trace(" Connected"); - driver = e.target as Socket; - driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); - } - - private function Quit() - { - fscommand("quit"); - try - { - NativeApplication.nativeApplication.exit(); - } catch (e) - { - - } - } - - private var jobQueue:Array = new Array(); - private var activeJob:Job = null; - private function QueueJob(jobParams) - { - if (!jobParams.hasOwnProperty("id")) - { - Print("Failure: job details didn't contain job id"); - CheckNewJob(); - return; - } - var id:int = parseInt(jobParams.id); - - if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") - { - Print("Failure: job " + id + " details didn't contain graphics array"); - JobFailed(id); - return; - } - var graphicsDetails:Array = jobParams.graphics; - - delete jobParams.command; - delete jobParams.id; - delete jobParams.graphics; - - var job:Job = new Job(id, graphicsDetails); - jobQueue.push(job); - CheckNewJob(); - } - - private function JobFailed(id:int) - { - DriverCommand("done", {id:id}); - CheckNewJob(); - } - - private function CheckNewJob() - { - if (activeJob == null && jobQueue.length > 0) - { - activeJob = jobQueue.shift(); - activeJob.Go(JobComplete); - } - } - - private function JobComplete() - { - Trace("Done: " + activeJob.GetID()); - - var data = activeJob.GetData(); - var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); - DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); - - activeJob = null; - CheckNewJob(); - } - - private function DispatchCommand(cmdData) - { - try - { - if (cmdData.hasOwnProperty("command")) - { - var cmd = "" + cmdData.command; - //Trace("cmd: " + cmd); - switch (cmd) - { - case "trace": - Trace(cmdData.string); - break; - case "exit": - Quit(); - break; - case "job": - QueueJob(cmdData); - break; - default: - Trace("Recv unknown: " + JSON.stringify(cmdData)); - break; - } - } - } catch (e) - { - Print(e.getStackTrace()); - } - } - - private var buffer:ByteArray = new ByteArray(); - private var swpBuffer:ByteArray = new ByteArray(); - private function DriverRecv(e) - { - var oldPos = buffer.position; - //Trace("recv"); - try - { - driver.readBytes(buffer, buffer.length, driver.bytesAvailable); - //Trace(buffer.length - buffer.position); - var len:uint = buffer.readUnsignedInt(); - var msg = buffer.readUTFBytes(len); - - buffer.readBytes(swpBuffer); - buffer.clear(); - - var tmp = buffer; - buffer = swpBuffer; - swpBuffer = tmp; - - var cmdData = JSON.parse(msg); - DispatchCommand(cmdData); - } - catch (eof:EOFError) - { - buffer.position = oldPos; - //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); - // wait for more data - } - catch (err:IOError) - { - Trace("Driver IO error"); - } - catch (err) - { - Trace("Problem reading from driver:\n" + err.toString()); - } - } - - private function DriverCommand(cmd:String, data = null) - { - var obj = {command:cmd}; - if (data != null) - { - for (var k in data) - { - obj[k] = data[k]; - } - } - var str:String = JSON.stringify(obj); - DriverSend(str); - } - - private function DriverSend(str:String) - { - if (driver != null) - { - driver.writeUnsignedInt(uint(str.length)); - driver.writeUTFBytes(str); - driver.flush(); - } - } - - public function Trace(str) - { - str = "" + str; - traceText.x = 2; - - trace(str); - traceText.width = stage.stageWidth - 4; - traceText.height = stage.stageHeight + 100; - if (traceText.text == "") - { - traceText.text = str; - } - else - { - traceText.appendText("\n" + str); - } - while (traceText.textHeight > traceText.height) - { - var split = traceText.text.indexOf("\n"); - if (split == -1) - { - traceText.height = traceText.textHeight + 5; - break; - } - traceText.text = traceText.text.substr(split + 1); - } - traceText.y = stage.stageHeight - traceText.textHeight - 2; - } - - public function Print(str:String, localTrace:Boolean = true) - { - if (localTrace || driver == null) - { - Trace(str); - } - else - { - trace(str); - } - if (driver != null) - { - DriverCommand("print", {string:str + "\n"}); - } - } - } -} \ No newline at end of file diff --git a/Exporter.exe b/Exporter.exe deleted file mode 100755 index 96c6dda..0000000 --- a/Exporter.exe +++ /dev/null Binary files differ diff --git a/Exporter.fla b/Exporter.fla deleted file mode 100755 index 83dfa3e..0000000 --- a/Exporter.fla +++ /dev/null Binary files differ diff --git a/Exporter.swf b/Exporter.swf deleted file mode 100644 index ba2b0f3..0000000 --- a/Exporter.swf +++ /dev/null Binary files differ diff --git a/FileExportSet.as b/FileExportSet.as deleted file mode 100644 index 3df339d..0000000 --- a/FileExportSet.as +++ /dev/null @@ -1,127 +0,0 @@ -package { - - //import flash.filesystem.File; - import flash.utils.*; - import flash.net.*; - import flash.events.*; - - public class FileExportSet { - - var names = []; - var data = []; - - public function FileExportSet() {}; - - public function Add(filename, fileData) - { - names.push(filename); - data.push(fileData); - } - - public function AddJSONPNGSet(jsonPNGSet:JSONPNGSet) - { - jsonPNGSet.JSONData.files = []; - for (var i = 0; i < jsonPNGSet.PNGSheets.length; i++) - { - var numExt = (jsonPNGSet.PNGSheets.length > 1) ? "_"+i : ""; - Add(jsonPNGSet.AssetName+numExt+".png", jsonPNGSet.PNGSheets[i]); - jsonPNGSet.JSONData.files.push(jsonPNGSet.AssetName+numExt+".png"); - } - - Add(jsonPNGSet.AssetName+".json", jsonPNGSet.JSONString); - } - - public function AddFileExportSet(fileExportSet) - { - for (var i = 0; i < fileExportSet.names.length; i++) - { - this.names.push(fileExportSet.names[i]); - this.data.push(fileExportSet.data[i]); - } - } - - var completeCallback = null; - - /* Save Local */ - public function Save(callback) - { - completeCallback = callback; - OutputNextFile(null); - } - - public function OutputNextFile(e:Event) - { - if (names.length > 0) - { - var name = this.names.shift(); - var data = this.data.shift(); - var fr:FileReference = new FileReference(); - - var pathParts = name.split("/"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - pathParts = name.split("\\"); - if (pathParts.length > 1) name = pathParts[pathParts.length - 1]; - - fr.save(data, name); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - if(completeCallback) completeCallback(); - } - } - - /* Upload to Server */ - var uploadURL; - var uploadFolder; - public function Upload(uploadURL, uploadFolder, callback) - { - this.uploadURL = uploadURL; - this.uploadFolder = uploadFolder; - completeCallback = callback; - UploadNextFile(); - } - - public function UploadNextFile() - { - - if (names.length > 0) - { - var filename = this.names.shift(); - var data = this.data.shift(); - - var loader = new URLLoader(); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - if (!uploadFolder.charAt(uploadFolder.length - 1) == "/") uploadFolder = uploadFolder + "/"; - var uploadRequest:URLRequest = new URLRequest(this.uploadURL+"?name="+uploadFolder+filename); - uploadRequest.requestHeaders.push(header); - uploadRequest.method = URLRequestMethod.POST; - uploadRequest.data = data; - - loader.addEventListener(Event.COMPLETE, onLoaded); - loader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError); - - loader.load(uploadRequest); - - _strace("uploading "+filename); - - } else { - if(completeCallback) completeCallback(); - } - } - - public function onLoaded(event) - { - _strace("Upload Complete"); - UploadNextFile(); - } - - function catchIOError(event:IOErrorEvent) - { - _strace("Error caught: "+event.type); - } - - - } - -} diff --git a/FrameInfo.as b/FrameInfo.as deleted file mode 100755 index f74604c..0000000 --- a/FrameInfo.as +++ /dev/null @@ -1,20 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class FrameInfo - { - public var frame:BitmapData; - public var drawMatrix:Matrix; - public var sourceRect:Rectangle; - - public var rect:Rectangle; - public var sheetIndex:int; - public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) - { - frame = b; - this.drawMatrix = drawMatrix; - this.sourceRect = sourceRect; - } - } -} \ No newline at end of file diff --git a/FramePacker.as b/FramePacker.as deleted file mode 100755 index 1a987f3..0000000 --- a/FramePacker.as +++ /dev/null @@ -1,125 +0,0 @@ -package -{ - import flash.geom.*; - import flash.display.*; - public class FramePacker - { - public const MaxSize:int = 2048; - private var sheets:Array; // [RectanglePacker] - private var frames:Array; // [FrameInfo] - - public function GetSheets():Array - { - return sheets; - } - - public function FramePacker(frames:Array) - { - this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frame != null; }, this); - this.frames.sortOn("frame", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - } - - private function GetMaxSize(frames:Array):Point - { - if (frames.length == 0) return new Point(); - return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.width; }, this)), - Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frame.height; }, this))); - } - - private function GetArea(frames:Array):int - { - var area = 0; - for (var i in frames) - { - if (frames[i] is FrameInfo) - { - area += frames[i].frame.width * frames[i].frame.height; - } - if (frames[i] is BitmapData || frames[i] is Rectangle) - { - area += frames[i].width * frames[i].height; - } - } - return area; - } - - public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames - - private var callback; - public function Pack(callback) - { - this.callback = callback; - sheets = new Array(); - var index = 0; - while (index < frames.length) - { - var now:Array = frames.slice(index); - - var max:Point = GetMaxSize(now); - var area:int = GetArea(now); - - var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); - var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); - var sizeY:int = sizeX; - - var i; - - var startIndex = index; - var nodes:Array = new Array(); - while (startIndex == index) - { - nodes.length = 0; - var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); - //var sorted:Array = now.sortOn("frame", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); - - //for (var sortedI = 0; sortedI < now.length; sortedI++) - for (i = 0; i < now.length; i++) - { - //i = sorted[sortedI]; - var node:RectangleNode = sheet.Insert(now[i].frame.width, now[i].frame.height); - if (node == null) - { - break; - } - nodes.push(node); - } - if (nodes.length == now.length) - { - // stop the loop, attempt the 75% check here - index += nodes.length; - } - else - { - if (sizeX == sizeY) - { - sizeX *= 2; - } - else - { - sizeY *= 2; - } - if (sizeX > MaxSize || sizeY > MaxSize) - { - if (nodes.length == 0) - { - Exporter.Instance.Print("Failure: item too large to pack on sheet"); - callback(false); - return; - } - index += nodes.length; - } - } - } - - for (i = startIndex; i < index; i++) - { - frames[i].sheetIndex = sheets.length; - frames[i].rect = nodes[i - startIndex].Rect; - } - sheets.push(sheet); - } - - callback(true); - } - } -} \ No newline at end of file diff --git a/GraphicExport.as b/GraphicExport.as deleted file mode 100644 index c46c218..0000000 --- a/GraphicExport.as +++ /dev/null @@ -1,461 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.display.Loader; - import flash.events.*; - import flash.text.*; - import flash.net.URLRequest; - import flash.utils.*; - import flash.net.*; - import flash.ui.Keyboard; - import flash.utils.getTimer; - import flash.geom.*; - import flash.display.StageAlign; - import flash.display.StageScaleMode; - import com.adobe.crypto.MD5; - import flash.system.fscommand; - import flash.desktop.*; - - import djarts.core.*; - import djarts.events.*; - import djarts.components.*; - import djarts.utils.*; - import djarts.resources.*; - import djarts.display.*; - - import djarts.utils.Base64; - import com.adobe.images.JPGEncoder; - import flash.display.BitmapData; - - import com.adobe.serialization.json.JSON; - import com.adobe.serialization.json.*; - import flash.display.Stage3D; - import flash.display.Bitmap; - import Packer.AsyncGraphicPacker; - import Defs.GraphicDef; - import Defs.HeroDef; - import CharacterExport.CharacterExporter; - import CharacterExport.ExportBuilder; - import CharacterExport.PieceLibrary; - import GraphicExport.IconPacker; - import GraphicExport.SkelAnimPacker; - import Defs.MapDef; - import GraphicExport.AnimSetPacker; - import GraphicExport.AnimPiecePacker; - import GraphicExport.ScenePacker; - - import flash.filesystem.*; - - public class GraphicExport extends MovieClip - { - - var UILayer:MovieClip = new MovieClip(); - public static var ISLOCAL = true; - public static var wrapper:Socket = null; - private static var instance:GraphicExport = null; - public function GraphicExport() - { - instance = this; - GraphicFactory.FAILEDGRAPHICASBLANK = true; - GameSettings.ISLOCAL = true; - - DialogManager.Instance().SetUILayer(UILayer); - DialogManager.Instance().SetUIOverLayer(UILayer); - - DialogManager.Instance().ResolutionChanged(stage.width, stage.height); - - this.stage.addChild(UILayer); - - this.removeChild(newGraphicDialog); - - Init(); - - try - { - NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); - } - catch (e) - { - // not an air runtime app - ConnectWrapper(7890); // try default port - } - - } - - public function ApplicationInvoked(e) - { - if (e.arguments.length == 1) - { - ConnectWrapper(parseInt(e.arguments[0])); - } - else - { - StartUI(); - } - } - - private function WrapperIOError(e) - { - Log("Couldn't connect wrapper"); - Log(e.toString()); - StartUI(); - } - - private function WrapperConnect(e:Event) - { - wrapper = e.target as Socket; - Log("Wrapper Connected"); - _strace("Wrapper Connected"); - wrapper.addEventListener(ProgressEvent.SOCKET_DATA, WrapperData); - - FlashConsole.Instance().Show(); - } - - private function WrapperData(e:ProgressEvent) - { - var data:String = wrapper.readUTF(); - DispatchCommand(com.adobe.serialization.json.JSON.decode(data)); - } - - private var inJob = false; - private var jobs:Array = new Array(); - - private function DispatchCommand(msg) - { - Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - if (msg.hasOwnProperty("command")) - { - var cmd = msg.command; - switch (cmd) - { - case "job": - jobs.push(msg); - CheckNewJob(); - break; - case "quit": - Log("Quitting"); - fscommand("quit"); - NativeApplication.nativeApplication.exit(); - break; - case "log": - Log(cmd.string); - break; - default: - //Log("Sent command: " + com.adobe.serialization.json.JSON.encode(msg)); - break; - } - } - } - - private function CheckNewJob() - { - if (!inJob && jobs.length > 0) - { - var job = jobs.shift(); - inJob = true; - - NewGraphicDialog.fakeID++; - - var graphicData = {id:NewGraphicDialog.fakeID,graphic:job.input,v:1,fs:0,p:0,type:job.type}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new Defs.GraphicDef(graphicData); - - ExportItem(graphicDef, - function() - { - SendCommand({command:"done", job_num:parseInt(job.job_num)}); - inJob = false; - CheckNewJob(); - } - ); - } - } - - public static function SendCommand(obj) - { - if (wrapper != null) - { - wrapper.writeUTF(com.adobe.serialization.json.JSON.encode(obj)); - wrapper.flush(); - //if (obj.hasOwnProperty("command") && obj.command == "print") - //{ - // instance.Log(obj.string); - //} - } - } - - private function ConnectWrapper(port) - { - Log("Attempting to connect wrapper"); - try - { - var s = new Socket(); - s.addEventListener(IOErrorEvent.IO_ERROR, WrapperIOError); - s.addEventListener(Event.CONNECT, WrapperConnect); - s.connect("localhost", port); - } catch (e) - { - Log("Error establishing wrapper connection"); - StartUI(); - return; - } - } - - - public function Init() - { - - _strace("Initializing game params!!"); - - //Set a scale mode for window resizing - stage.align = StageAlign.TOP_LEFT; - stage.scaleMode = StageScaleMode.NO_SCALE; - - GameSettings.GameplayArea = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); - - ResourceManager.Instance().Init(ISLOCAL, "RootGame"); - - ResourceManager.Instance().SetLocations([""]); - - GameSettings.Instance().SetStage(this.stage); - Globals.Instance().SetStage(this.stage); - - FlashConsole.Instance().Admin = true; - - - stage.addEventListener(Event.ENTER_FRAME, EnterFrame); - - this.addChild(previewHolder); - CreateUI(); - ActivateExportButtons(false); - } - - var exportButtons:Array = []; - public function ActivateExportButtons(active) - { - for(var i = 0; i < exportButtons.length; i++) - { - exportButtons[i].Enabled = active; - } - - this.heuristicCheck.Enabled = active; - this.edgeExpand.Enabled = active; - this.skeletal_scale.type = active ? TextFieldType.INPUT : TextFieldType.DYNAMIC; - } - - protected function CreateUI() - { - /* - var maxWidth = 0; - for (var i = 0; i < exportButtons.length; i++) maxWidth = Math.max(maxWidth, exportButtons[i].width); - - var startX = buttonArea.x + (maxWidth / 2); //stage.stageWidth - 110; - var startY = buttonArea.y + 20; - for(var i = 0; i < exportButtons.length; i++) - { - this.addChild(exportButtons[i]) - exportButtons[i].x = startX; - exportButtons[i].y = startY; - maxWidth = Math.max(maxWidth, exportButtons[i].width); - if (exportButtons[i].GetButtonText() == "Generic Use") - { - addChild(genericUseText); - genericUseText.x = startX - exportButtons[i].width / 2; - genericUseText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single ID") - { - addChild(singleIdText); - singleIdText.x = startX - exportButtons[i].width / 2; - singleIdText.y = startY + 18; - startY += 25; - } - - if (exportButtons[i].GetButtonText() == "Single Asset") - { - addChild(singleAssetText); - singleAssetText.x = startX - exportButtons[i].width / 2; - singleAssetText.y = startY + 18; - startY += 25; - } - - startY += 35; - if (startY > buttonArea.y + buttonArea.height - 20) - { - startY = buttonArea.y + 20; - startX += (maxWidth + 20); - maxWidth = 0; - } - } - */ - - heuristicCheck.Checked = false; - heuristicCheck.OnClickParam = heuristicCheck; - heuristicCheck.OnClick = ClickedHeuristic; - heuristicCheck.Text = "Flat Animated Clip Heuristic"; - - edgeExpand.Checked = false; - edgeExpand.OnClickParam = edgeExpand; - edgeExpand.OnClick = ClickedEdgeExpand; - edgeExpand.Text = "Expand edge alpha."; - - PNGExportHelper.UseExpandedBitmaps = true; - edgeExpand.Checked = PNGExportHelper.UseExpandedBitmaps; - - this.skeletal_scale.addEventListener(Event.CHANGE, SkeletalScaleChanged); - } - - public function StartUI() - { - ActivateExportButtons(true); - ShowNewGraphicDialog(); - } - - public function ShowNewGraphicDialog() - { - newGraphicDialog.Show(this); - } - - var skeletalScale = 1; - private function SkeletalScaleChanged(e:Event) - { - try - { - var number = Number(skeletal_scale.text); - skeletalScale = number; - } catch(exception){ - - } - } - - private function ClickedHeuristic(button:Checkbox) - { - AsyncGraphicPacker.UseFlatHeuristic = !AsyncGraphicPacker.UseFlatHeuristic; - button.Checked = AsyncGraphicPacker.UseFlatHeuristic; - } - - private function ClickedEdgeExpand(button:Checkbox) - { - PNGExportHelper.UseExpandedBitmaps = !PNGExportHelper.UseExpandedBitmaps; - button.Checked = PNGExportHelper.UseExpandedBitmaps; - } - - var outputFormat = "json_png_set"; - - protected var lastTime = null; - protected function EnterFrame(e:Event) - { - var now = getTimer() / 1000.0; - if (lastTime == null) lastTime = now; - - var timeElapsed = now - lastTime; - - ResourceManager.Instance().StartUpdateLoop(); - - EnterFrameManager.Instance().EnterFrame(new TimeElapsedEvent(timeElapsed), timeElapsed); - - ResourceManager.Instance().EndUpdateLoop(); - - HeroSpriteLoader.Instance().Update(1); - - lastTime = now; - } - - protected var graphicPreloader:GraphicPreloader = new GraphicPreloader(); - - protected function DoneAll() - { - ActivateExportButtons(true); - _strace("========= DONE ALL ========="); - } - - protected var lastCallback; - public function ExportItem(def:Defs.GraphicDef, callback = null) - { - this.lastCallback = callback; - Log("Exporting " + def.ID + " " + def != null); - var graphicDefs:Array = [def]; - - var type = def.Type; - - var assetDef:Defs.GraphicDef = null; - if (def.ExportParams.hasOwnProperty("asset_id")) - { - assetDef = GameData.Instance().GetGraphicDefByID(def.ExportParams.asset_id); - type = assetDef.Type; - } - Log(" type: " + type); - switch (type) - { - case Defs.GraphicDef.EXPORT_FORMAT_SPRITESHEET: - if (def.ExportParams.hasOwnProperty("export_animation")) - { - var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - graphicPacker.ExportDefs(graphicDefs, DoneAsset, def, outputFormat); - } else { - var iconPacker:IconPacker = new IconPacker(DoneAsset, def, previewHolder, outputFormat); - iconPacker.ExportDefs(graphicDefs); - } - break; - case Defs.GraphicDef.EXPORT_FORMAT_CACHEDCLIP: - break; - case Defs.GraphicDef.EXPORT_FORMAT_SKELANIM: - var skelPacker:SkelAnimPacker = new SkelAnimPacker(DoneAsset, def, previewHolder, - assetDef && assetDef.ExportParams.hasOwnProperty("export_type") ? assetDef.ExportParams.export_type : null, skeletalScale, outputFormat); - skelPacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMSETS: - var animSetPacker:AnimSetPacker = new AnimSetPacker(DoneAsset, def, previewHolder); - animSetPacker.ExportDef(graphicDefs[0]); - break; - case Defs.GraphicDef.EXPORT_FORMAT_ANIMPIECES: - var animPiecePacker:AnimPiecePacker = new AnimPiecePacker(DoneAsset, def, previewHolder); - animPiecePacker.ExportDefs(graphicDefs); - break; - case Defs.GraphicDef.EXPORT_FORMAT_SCENE: - var scenePacker:ScenePacker = new ScenePacker(DoneAsset, def, previewHolder, outputFormat); - scenePacker.ExportDef(graphicDefs[0]); - break; - default: - _strace("COULDN'T DETERMINE EXPORT FORMAT"); - break; - } - } - - public function Log(logStr) - { - logText.text += logStr + "\n"; - } - - protected function DoneAsset(output, assetDef:Defs.GraphicDef) - { - Log(assetDef.Folder + assetDef.Name); - - var fileExport:FileExportSet = null; - - if (output is FileExportSet) fileExport = output; - if (output is JSONPNGSet) - { - fileExport = new FileExportSet(); - output.AssetName = assetDef.Name; - fileExport.AddJSONPNGSet(output); - } - - if (output is ByteArray) - { - fileExport = new FileExportSet(); - fileExport.Add(assetDef.Name, output); - } - - fileExport.Save(lastCallback); - - } - - - } - -} diff --git a/GraphicExport/AnimPiecePacker.as b/GraphicExport/AnimPiecePacker.as deleted file mode 100644 index 9bb912b..0000000 --- a/GraphicExport/AnimPiecePacker.as +++ /dev/null @@ -1,67 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimPiecePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimPiecePacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var defs:Array; - public function ExportDefs(defs:Array) - { - this.defs = defs; - - ExportNextDef(); - } - - protected function ExportNextDef() - { - if (defs.length == 0) - { - Done(); - } - else - { - var def:GraphicDef = defs.splice(0, 1)[0]; - var graphic = GraphicFactory.Instance().GetGraphic(def.Name, null, function(c, g){GraphicCallback(c,g,def);}); - } - } - - protected var toExport:Array = new Array(); - - protected function GraphicCallback(c, g, def:GraphicDef) - { - if (g is MovieClip) - { - var pieceSet:AnimationPieceSet = new AnimationPieceSet(); - pieceSet.Name = def.Name; - toExport.push(pieceSet); - pieceSet.LoadClip(g, ExportNextDef); - } - else - { - ExportNextDef(); - } - } - - protected function Done() - { - var builder:AnimPieceExportBuilder = new AnimPieceExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/AnimSetPacker.as b/GraphicExport/AnimSetPacker.as deleted file mode 100644 index 602e237..0000000 --- a/GraphicExport/AnimSetPacker.as +++ /dev/null @@ -1,81 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - - public class AnimSetPacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - public function AnimSetPacker(callback, callbackParam, holder:MovieClip) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - } - - protected var avatarIndex = 0; - protected var avatars:Array; - public function ExportDef(def:GraphicDef) - { - avatarIndex = 0; - avatars = def.ExportParams.avatars; - DoNextAvatar(); - } - - private function DoNextAvatar() - { - if (avatarIndex >= avatars.length) - { - Done(); - return; - } - var avatar = avatars[avatarIndex]; - - - var graphic = GraphicFactory.Instance().GetGraphic(avatar.base_clip, null, GraphicCallback); - } - - protected var exporter:CharacterExporter; - protected function GraphicCallback(c, g) - { - exporter = new CharacterExporter(holder); - exporter.ProcessFromClip(g, ProductionDone); - } - - protected var toExport:Array = new Array(); - - protected function ProductionDone() - { - var avatar = avatars[avatarIndex]; - var avatarName = avatar.avatar; - var animations:Array = avatar.animations; - - for (var i in exporter.Sequences) - { - exporter.Sequences[i].AvatarName = avatarName; - if (animations.indexOf(exporter.Sequences[i].AnimationName) != -1) - { - toExport.push(exporter.Sequences[i]); - } - } - - avatarIndex++; - - //exporter.ProduceTemplate(DoNextAvatar); - DoNextAvatar(); - } - - protected function Done() - { - var builder:AnimSetExportBuilder = new AnimSetExportBuilder(toExport); - - if (doneCallback) doneCallback(builder.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExport/IconPacker.as b/GraphicExport/IconPacker.as deleted file mode 100644 index e8df65e..0000000 --- a/GraphicExport/IconPacker.as +++ /dev/null @@ -1,394 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import djarts.utils.CountWaiter; - import djarts.core.*; - import djarts.display.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import Packer.SpriteSheet; - import flash.geom.Matrix; - import flash.utils.*; - import flash.display.MovieClip; - import flash.display.BitmapData; - import flash.display.Bitmap; - import djarts.utils.SimpleTimer; - import flash.display.*; - import flash.geom.ColorTransform; - - public class IconPacker - { - protected var doneCallback = null; - protected var callbackParam; - protected var holder:MovieClip; - protected var jsonSpriteData = {}; - protected var pngSheets = []; - - public var outputFormat = "binary"; - - public function IconPacker(callback, callbackParam, holder:MovieClip, outputFormat) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - - jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - - output.endian = Endian.LITTLE_ENDIAN; - } - - protected var pageWidth = 2048; - protected var pageHeight = 2048; - - protected var defs:Array; - - protected var pad = 3; - - public function ExportDefs(defs:Array) - { - if (defs.length == 1) - { - ExportSingle(defs[0]) - } - else - { - this.defs = defs; - Export(); - } - } - - public function ExportSingle(def:GraphicDef) - { - this.defs = [def]; - var g = GraphicFactory.Instance().GetGraphicByID(def.ID, null, CheckSizesForSingle); - if (GraphicFactory.Instance().LoadedOK(g)) - { - CheckSizesForSingle(null, g); - } - } - - protected function CheckSizesForSingle(caller, g) - { - var p:Point = Pow2SizeForGraphic(defs[0]); - pageWidth = p.x; - pageHeight = p.y; - - Export(); - } - - protected function Pow2SizeForGraphic(def:GraphicDef):Point - { - var g = GraphicFactory.Instance().GetGraphicByID(def.ID); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (def.ExportParams.hasOwnProperty("available_sizes")) - { - var totalSize = 0; - for (var i in def.ExportParams.available_sizes) - { - if (def.ExportParams.available_sizes[i] == "default") - { - var largestSide = Math.max(bounds.width + pad * 2, bounds.height + pad * 2); - totalSize += largestSide * largestSide; - } else { - var parts:Array = def.ExportParams.available_sizes[i].split("x"); - if (parts.length == 2) - { - var w = Number(parts[0]) + pad * 2; - var h = Number(parts[1]) + pad * 2; - totalSize += w * h; - } - } - } - - var size = Math.sqrt(totalSize); - var exponent = Math.ceil(Math.log(size) / Math.log(2)); - size = Math.pow(2, exponent); - return new Point(size, size); - } else { - var exponentX = Math.ceil(Math.log(bounds.width + pad * 2) / Math.log(2)); - var exponentY = Math.ceil(Math.log(bounds.height + pad * 2) / Math.log(2)); - return new Point(Math.pow(2, exponentX), Math.pow(2, exponentY)); - } - } - - protected var sheets:Array = new Array(); - - protected var totalSprites = 0; - protected var output:ByteArray = new ByteArray(); - - protected var lastGraphic = null; - - protected var currentDef:GraphicDef; - protected function Export() - { - var sheet:SpriteSheet = new SpriteSheet(pageWidth, pageHeight); - sheets.push(sheet); - holder.AddClip(new Bitmap(sheet.GetBitmap())); - ExportNext(); - } - - protected function ExportNext() - { - _strace("Exporting " + defs.length); - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - protected function GraphicLoaded(caller, g) - { - _strace(currentDef.Name); - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(g, 2048); - - if (currentDef.ExportParams.hasOwnProperty("available_sizes")) - { - for (var j in currentDef.ExportParams.available_sizes) - { - if (currentDef.ExportParams.available_sizes[j] == "default") - { - AddGraphicAtSize(currentDef, g, 1, bounds, Math.ceil(bounds.width), Math.ceil(bounds.height), true); - } else { - var parts:Array = currentDef.ExportParams.available_sizes[j].split("x"); - if (parts.length == 2) - { - var width = Number(parts[0]); - var height = Number(parts[1]); - var scale = Math.min(width / bounds.width, height / bounds.height); - AddGraphicAtSize(currentDef, g, scale, bounds, width, height); - } - } - } - } else { - AddGraphicAtSize(currentDef, g, 1, bounds); - } - - if (holder) - { - - - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - holder.addChild(g); - lastGraphic = g; - g.x = 150; - g.y = 150; - - bitmapPreview.x = g.x; - bitmapPreview.y = g.y + 150; - - holder.addChild(bitmapPreview); - } - - - ExportNext(); - } - - protected var bitmapPreview:MovieClip = new MovieClip(); - public static const VERSION = 2; - - protected function Done() - { - var stream:ByteArray = new ByteArray(); - stream.endian = Endian.LITTLE_ENDIAN; - - // -1 is an unlikely number of sheets to have, so - // I use this as a marker that this file has a version number in it - stream.writeInt(-1); - stream.writeInt(VERSION); - - stream.writeInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - stream.writeInt(pageWidth); - stream.writeInt(pageHeight); - - var data:ByteArray = PNGExportHelper.GetExportPNG(sheets[i].GetBitmap()); - stream.writeInt(data.length); - stream.writeBytes(data); - - pngSheets.push(data); - } - - stream.writeInt(totalSprites); - stream.writeBytes(output); - - var jsonPngSet = new JSONPNGSet(jsonSpriteData.graphics[0].Name, jsonSpriteData, pngSheets); - //jsonSpriteData - - if (doneCallback) - { - - doneCallback(outputFormat == "binary" ? stream : jsonPngSet, callbackParam); - } - - var t:SimpleTimer = new SimpleTimer(2, ClearPreview); - - } - - protected function ClearPreview() - { - if (holder) - { - if (lastGraphic) - { - if (holder.contains(lastGraphic)) holder.removeChild(lastGraphic); - } - //while(holder.numChildren > 0) holder.removeChildAt(0); - } - } - - protected function AddGraphicAtSize(def:GraphicDef, g, scale, bounds:Rectangle, availWidth = null, availHeight = null, isDefault = false) - { - totalSprites++; - output.writeUnsignedInt(def.Name.length); - output.writeMultiByte(def.Name, "us-ascii"); - - var spriteData = {}; - jsonSpriteData.graphics.push(spriteData); - spriteData.name = def.Name; - - var hasSize = (availWidth != null && availHeight != null); - output.writeBoolean(hasSize); - if (hasSize) - { - output.writeBoolean(isDefault); - output.writeInt(availWidth); - output.writeInt(availHeight); - - spriteData.defaultSize = isDefault; - spriteData.sizeX = availWidth; - spriteData.sizeY = availHeight; - } - output.writeInt(1); // num sequences - output.writeInt(1); // num frames - - spriteData.sequences = []; - spriteData.sequences.push([]); - var frame = {}; - spriteData.sequences[0].push(frame); - - var b:Rectangle = bounds.clone(); - b.left = Math.floor(bounds.left * scale); - b.right = Math.ceil(bounds.right * scale); - b.top = Math.floor(bounds.top * scale); - b.bottom = Math.ceil(bounds.bottom * scale); - - var newSheet = false; - var found = false; - for (var s = 0; s < sheets.length; s++) - { - var node:RectangleNode = sheets[s].GetAllocator().Insert(b.width + pad * 2, b.height + pad * 2); - if (node) - { - output.writeInt(s); // sheet index - - // rectangle - output.writeFloat(node.Rect.left + pad); - output.writeFloat(node.Rect.top + pad); - output.writeFloat(node.Rect.width - (pad * 2)); - output.writeFloat(node.Rect.height - (pad * 2)); - output.writeFloat(-b.left); - output.writeFloat(-b.top); - - frame.texture = s; - frame.tx = node.Rect.left + pad; - frame.ty = node.Rect.top + pad; - frame.tw = node.Rect.width - (pad * 2); - frame.th = node.Rect.height - (pad * 2); - frame.x = -b.left; - frame.y = -b.top; - - sheets[s].GetBitmap().draw(g, new Matrix(scale, 0, 0, scale, -b.left + pad + node.Rect.left, -b.top + pad + node.Rect.top), null, BlendMode.NORMAL, - new Rectangle(node.Rect.left + pad, // note: bitmap space! - node.Rect.top + pad, - node.Rect.width - pad * 2, - node.Rect.height - pad * 2)); - found = true; - break; - } - if (!found && s == sheets.length - 1) - { - if (newSheet) - { - throw new Error("Bad sprite!"); - return; - } - newSheet = true; - sheets.push(new SpriteSheet(pageWidth, pageHeight)); - - holder.AddClip(new Bitmap(sheets[sheets.length - 1].GetBitmap())); - } - } - - - } - - public function RemoveSmallChildren(clip:MovieClip) - { - if (clip.height < 35 && clip.parent != null) - { - clip.visible = false; - _strace("removed clip that was "+clip.height+ " tall"); - } - for(var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - RemoveSmallChildren(clip.getChildAt(i) as MovieClip); - } - } - } - - public function RecursiveCacheAsBitmap(clip:MovieClip) - { - clip.cacheAsBitmap = true; - for(var i = 0; i < clip.numChildren; i++){ - if (clip.getChildAt(i) is MovieClip) - { - RecursiveCacheAsBitmap(clip.getChildAt(i) as MovieClip); - } - } - } - - protected var cw:CountWaiter; - protected var loadCallback; - protected function LoadAll(defs:Array, callback) - { - loadCallback = callback; - cw = new CountWaiter(LoadDone); - - for (var i in defs) - { - cw.Wait(); - GraphicFactory.Instance().MakeLoadOrFailCallbackByID(defs[i].ID, cw.WaitDone); - GraphicFactory.Instance().GetGraphicByID(defs[i].ID, null, BlankCallback); - } - - cw.Go(); - } - - protected function BlankCallback(...rest) - { - } - - protected function LoadDone(waiter) - { - if (loadCallback) loadCallback(); - } - } -} \ No newline at end of file diff --git a/GraphicExport/ScenePacker.as b/GraphicExport/ScenePacker.as deleted file mode 100644 index e2e025b..0000000 --- a/GraphicExport/ScenePacker.as +++ /dev/null @@ -1,301 +0,0 @@ -package GraphicExport -{ - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - import djarts.display.GraphicFactory; - import CharacterExport.*; - import flash.utils.ByteArray; - import Packer.SpriteSheet; - import flash.utils.Endian; - import Packer.GraphicPacker; - import Packer.AsyncGraphicPacker; - import flash.net.FileReference; - import flash.display.Bitmap; - import com.adobe.serialization.json.JSON; - import flash.geom.Matrix; - - public class ScenePacker - { - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - - protected var sheets:Array = new Array(); - protected var output:ByteArray = new ByteArray(); - - public function ScenePacker(callback, callbackParam, holder:MovieClip, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.outputFormat = outputFormat; - graphicPacker.outputFormat = outputFormat; - } - - var currentDef:GraphicDef = null; - public function ExportDef(def:GraphicDef) - { - this.currentDef = def; - graphicPacker.outputAssetName = def.Name+"_graphics"; - var graphic = GraphicFactory.Instance().GetGraphicByID(def.ID, null, SceneGraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(graphic)) SceneGraphicLoaded(null, graphic); - } - - - var clipData:Array; - protected function SceneGraphicLoaded(c, g:MovieClip) - { - - // read out the clips and transform data for the items on the graphic. - clipData = new Array(); - - //Need to find any drawing objects that are not movie clips and give them thier own clip so they process correctly. - var gSymbols:MovieClip = new MovieClip(); - var symbolsToMove = new Array(); - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip) symbolsToMove.push(child); - } - - for (var i = 0; i < symbolsToMove.length; i++) gSymbols.addChild(symbolsToMove[i]); - - //if there are still drawing objects that were not movie clips add them as the background. - if (g.width > 0) gSymbols.addChildAt(g, 0); - - //This reorganized clip is now the clip to export. - g = gSymbols; - - //Chunk Large Children... This breaks up clips that are large than 1024 into smaller pieces. - //This helps with large backgrounds and doesn't require 2048x2048 textures which end up wasting a lot of space. - for (var i = 0; i < g.numChildren; i++) - { - var child = g.getChildAt(i) as MovieClip; - if (child is MovieClip && (child.width > 1024 || child.height > 1024)) - { - var chunkedChild = new ChunkedGraphic(child, 500); - _strace("Chunked child graphic, added "+chunkedChild.numChildren+" chunks!"); - g.removeChildAt(i); - var chunkID = 0; - - var toAdd = chunkedChild.numChildren; - - while(chunkedChild.numChildren > 0) - { - var chunkedChildChunk = chunkedChild.getChildAt(0); - chunkedChildChunk.name = child.name +"_chunk"+chunkID++; - - var m1:Matrix = chunkedChildChunk.transform.matrix.clone(); - //var m2:Matrix = child.transform.matrix.clone(); - - m1.concat(child.transform.matrix); - //m2.concat(chunkedChildChunk.transform.matrix); - - chunkedChildChunk.transform.matrix = m1; - - /* - // since the scale information is removed (by exporting the sprite sheet at scale) - // we only need the corrected x/y components here - chunkedChildChunk.x = m1.tx; - chunkedChildChunk.y = m1.ty; - */ - - //chunkedChildChunk.x += chunkedChild.x; - //chunkedChildChunk.y += chunkedChild.y; - - g.addChildAt(chunkedChildChunk, i); - } - - i += Math.max(0, toAdd - 1); - } - } - - for (var i = 0; i < g.numChildren; i++) - { - if (g.getChildAt(i) is MovieClip) - { - var child:MovieClip = g.getChildAt(i) as MovieClip; - var frameCount = GetLongestSequenceLength(child); - - var type = GraphicDef.EXPORT_FORMAT_SPRITESHEET; - if (frameCount > 1) - { - type = GraphicDef.EXPORT_FORMAT_SKELANIM; - } - - var name = child.name; - - var transformData = CharacterExporter.Decompose(child.transform.matrix); - //var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":transformData.sx, "scaleY":transformData.sy, "rotation":transformData.rot}; - var childData = {"clip":child, "index":i, "type":type, "name":name, "x":child.x, "y": child.y, "scaleX":1, "scaleY":1, "rotation":transformData.rot}; - clipData.push(childData); - - var str = ""; - for(var key in childData) - { - str += key + " => " + childData[key] + " "; - } - _strace(str); - } - } - - ExportNext(); - } - - var clipIndex:int = 0; - protected function ExportNext() - { - if (clipIndex < clipData.length) - { - var data = clipData[clipIndex++]; - switch(data.type) - { - case GraphicDef.EXPORT_FORMAT_SKELANIM : AddSkeletalClip(data.clip, Math.max(data.scaleX, data.scaleY) ); break; - case GraphicDef.EXPORT_FORMAT_SPRITESHEET : AddGraphicClip(data.clip); break; - } - - } else { - ProcessGraphicExporter(); - } - } - - protected function ProcessGraphicExporter() - { - //actually does the writing to sprite sheets and creating the output bytes. - graphicPacker.ExportClips(graphicExporterClipList, ProcessGraphicExporterDone); - this.holder.AddClip(new Bitmap(graphicPacker.GetSheets()[0].GetBitmap() ) ); - } - - protected function ProcessGraphicExporterDone(output) - { - Done(); - } - - protected var skelExporters:Array = new Array(); - var library:PieceLibrary = new PieceLibrary(); - protected function AddSkeletalClip(clip:MovieClip, upscale:Number) - { - var characterExporterPreviewClip = new MovieClip(); - this.holder.AddClip(characterExporterPreviewClip); - - var exporter:CharacterExporter = new CharacterExporter(characterExporterPreviewClip); - skelExporters.push(exporter); - exporter.Upscale = upscale; - exporter.GraphicName = clip.name; - exporter.ProcessFromClip(clip, ExportNext, library); - } - - var graphicExporterClipList:Array = new Array(); - protected var graphicPacker:AsyncGraphicPacker = new AsyncGraphicPacker(); - protected function AddGraphicClip(clip:MovieClip) - { - graphicExporterClipList.push(clip); - ExportNext(); - } - - protected function GetLongestSequenceLength(clip:MovieClip, count:int = 1):int - { - if (clip.totalFrames > count) count = clip.totalFrames; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - count = GetLongestSequenceLength(clip.getChildAt(i) as MovieClip, count); - } - } - return count; - } - - var outputFormat = "binary"; - - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - var exporter:ExportBuilder = new ExportBuilder(skelExporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - var fileExportSet = new FileExportSet(); - - var skelPNGSet = exporter.GetJSONPNGSet(); - var graphicPNGSet = graphicPacker.GetJSONPNGSet(); - - skelPNGSet.AssetName = this.currentDef.Name+"_skel"; - graphicPNGSet.AssetName = this.currentDef.Name+"_graphics"; - - //graphicPNGSet.JSONData.meta.image = this.currentDef.Name+"_graphics.png"; - - var jsonOutput = {}; - jsonOutput.name = currentDef.Name; - jsonOutput.format = "scene"; - if (skelPNGSet.PNGSheets.length > 0) jsonOutput.skeletal_asset = this.currentDef.Name + "_skel.json"; - jsonOutput.graphic_asset = this.currentDef.Name + "_graphics.json"; - - jsonOutput.clips = []; - for(var i = 0; i < clipData.length; i++) - { - var jsonClipData = {}; - - jsonClipData.type = clipData[i].type; - jsonClipData.name = clipData[i].name; - - jsonClipData.x = clipData[i].x; - jsonClipData.y = clipData[i].y; - jsonClipData.sx = clipData[i].scaleX; - jsonClipData.sy = clipData[i].scaleY; - jsonClipData.rot = clipData[i].rotation; - - jsonOutput.clips.push(jsonClipData); - } - - var jsonDataOutput = com.adobe.serialization.json.JSON.encode(jsonOutput); - fileExportSet.Add(currentDef.Name+".json", jsonDataOutput); - fileExportSet.AddJSONPNGSet(graphicPNGSet); - if (skelPNGSet.PNGSheets.length > 0) fileExportSet.AddJSONPNGSet(skelPNGSet); - - if (doneCallback) doneCallback(fileExportSet, callbackParam); - - } else { - - var skelData:ByteArray = exporter.Output; - var graphicData:ByteArray = graphicPacker.GetOutput(); - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(currentDef.Name.length); - output.writeMultiByte(currentDef.Name, "us-ascii"); - - output.writeUnsignedInt(clipData.length); - for(var i = 0; i < clipData.length; i++) - { - output.writeUnsignedInt(clipData[i].type); - output.writeUnsignedInt(clipData[i].name.length); - output.writeMultiByte(clipData[i].name, "us-ascii"); - - output.writeInt(clipData[i].x); - output.writeInt(clipData[i].y); - output.writeDouble(clipData[i].scaleX); - output.writeDouble(clipData[i].scaleY); - output.writeDouble(clipData[i].rotation); - } - - output.writeUnsignedInt(skelData.length); - output.writeBytes(skelData); - - output.writeUnsignedInt(graphicData.length); - output.writeBytes(graphicData); - - if (doneCallback) doneCallback(output, callbackParam); - } - - //Clear the Preview - //while(this.holder.numChildren > 0) holder.removeChildAt(0); - - - - } - } -} \ No newline at end of file diff --git a/GraphicExport/SkelAnimPacker.as b/GraphicExport/SkelAnimPacker.as deleted file mode 100644 index bbbdec3..0000000 --- a/GraphicExport/SkelAnimPacker.as +++ /dev/null @@ -1,101 +0,0 @@ -package GraphicExport -{ - import CharacterExport.*; - import Defs.GraphicDef; - import flash.display.MovieClip; - import djarts.utils.*; - - - public class SkelAnimPacker - { - - protected var library:PieceLibrary; - protected var waiter:CountWaiter; - - protected var exporters:Array = new Array(); - - protected var defs:Array = new Array(); - - protected var doneCallback; - protected var callbackParam; - protected var holder:MovieClip; - protected var defaultExportType; - protected var scale:Number = 1; - - protected var outputFormat = "binary"; - - public function SkelAnimPacker(callback, callbackParam, holder:MovieClip, defaultExportType = null, scale=1, outputFormat="binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.holder = holder; - this.defaultExportType = defaultExportType; - this.scale = scale; - this.outputFormat = outputFormat; - } - - public function ExportDefs(defs:Array) - { - this.defs = defs; - - library = new PieceLibrary(); - - ExportNext(); - } - - var removeClips:Array = new Array(); - - protected var currentDef:GraphicDef; - protected function ExportNext(...rest) - { - if (holder) - { - for (var i in removeClips) - { - if (removeClips[i].parent) - { - removeClips[i].parent.removeChild(removeClips[i]); - } - } - removeClips.splice(0); - - for (var i = 0; i < holder.numChildren; i++) - { - removeClips.push(holder.getChildAt(i)); - } - } - if (defs.length == 0) - { - Done(); - return; - } - - currentDef = defs.shift(); - - var exporter:CharacterExporter = new CharacterExporter(holder); - exporters.push(exporter); - - exporter.Process(currentDef.ID, ExportNext, library, defaultExportType, scale); - } - - var exporter:ExportBuilder; - protected function Done() - { - this.library.EnsureAllUsedPiecesHaveNames(); - - exporter = new ExportBuilder(exporters, -1, -1, library); - - if (outputFormat == "json_png_set") - { - if (doneCallback) doneCallback(exporter.GetJSONPNGSet(), callbackParam); - } else { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } - - protected function JSONSaveComplete() - { - if (doneCallback) doneCallback(exporter.Output, callbackParam); - } - } -} \ No newline at end of file diff --git a/GraphicExportDef.as b/GraphicExportDef.as deleted file mode 100755 index f3454a0..0000000 --- a/GraphicExportDef.as +++ /dev/null @@ -1,158 +0,0 @@ -package -{ - import flash.utils.*; - import flash.display.*; - import flash.system.LoaderContext; - import flash.events.*; - import by.blooddy.crypto.*; - import flash.system.SecurityDomain; - - public class GraphicExportDef - { - public const TYPE_SPRITES = 1; - public const TYPE_SKELETAL = 2; - - private var _exportType:int = 1; - public function get exportType():int { return _exportType; } - - private var _className:String = null; - public function get className():String { return _className; } - - private var _name:String = null; - public function get name():String { return _name; } - - private var _valid:Boolean = false; - public function get valid():Boolean { return _valid; } - - private var _padding:int = 0; - public function get padding():int { return _padding; } - - private var _scale:Number = 0; - public function get scale():Number { return _scale; } - - private var input:ByteArray; - private var inputLoader:Loader = null; - - private var parentJob:Job = null; - - private var callback = null; - - private var index:int = 0; - - public function GraphicExportDef(parentJob:Job, details, index:int) - { - this.parentJob = parentJob; - this.index = index; - if (!details.hasOwnProperty("type") || - !details.hasOwnProperty("name") || - !details.hasOwnProperty("input") || - !details.hasOwnProperty("class_name")) - { - Fail("graphic export is missing a required class_name, name, type, or input"); - return; - } - _exportType = parseInt(details.type); - _name = "" + details.name; - _className = "" + details.class_name; - input = Base64.decode("" + details.input); - _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; - _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; - _valid = true; - } - - public function Fail(err:String) - { - parentJob.FailMessage("(" + index + ")" + err); - _valid = false; - if (callback != null) callback(); - } - - public function Go(callback) - { - this.callback = callback; - - inputLoader = new Loader(); - inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); - inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); - var context:LoaderContext = new LoaderContext(); - context.allowCodeImport = true; - inputLoader.loadBytes(input, context); - } - - private var frames:IFramesSource = null; - - private function LoaderComplete(e) - { - try - { - var classDef = e.target.applicationDomain.getDefinition(className); - if (classDef == null) - { - Fail("didn't contain a definition for " + className); - return; - } - - var clip = new classDef(); - if (!(clip is MovieClip)) - { - Fail(className + " wasn't a movieclip"); - } - - Utils.RecursivelyStop(clip); - - frames = null; - - switch (exportType) - { - case TYPE_SPRITES: - frames = new AnimatedSpriteGenerator(clip, this); - break; - case TYPE_SKELETAL: - frames = new AnimatedSkeletonGenerator(clip, this); - break; - } - - if (frames == null) - { - Fail("invalid export type: " + exportType); - return; - } - - frames.Go(FramesDone); - - } catch (e) - { - Exporter.Instance.Print(e.getStackTrace()); - } - } - - private function FramesDone(success) - { - if (!success) - { - Fail("couldn't get source frames"); - return; - } - Done(); - } - - private function LoaderError(e) - { - Fail("couldn't load input: " + e.toString()); - } - public function Done() - { - this.callback(); - } - - public function GetFrames():Array - { - return frames.GetFrames(); - } - - public function GetData() - { - return frames.GetData(); - } - } -} \ No newline at end of file diff --git a/IFramesSource.as b/IFramesSource.as deleted file mode 100755 index a55f231..0000000 --- a/IFramesSource.as +++ /dev/null @@ -1,9 +0,0 @@ -package -{ - public interface IFramesSource - { - function Go(callback); - function GetFrames():Array; - function GetData(); - } -} \ No newline at end of file diff --git a/JSONPNGSet.as b/JSONPNGSet.as deleted file mode 100644 index 29ce742..0000000 --- a/JSONPNGSet.as +++ /dev/null @@ -1,31 +0,0 @@ -package { - - import com.adobe.serialization.json.JSON; - - public class JSONPNGSet - { - - public var AssetName = ""; - public var JSONData = ""; - public function get JSONString(){ return com.adobe.serialization.json.JSON.encode(JSONData); } - public var PNGSheets:Array = []; - - public function JSONPNGSet(assetName = "", JSONData = null, PNGSheets = null) - { - SetData(assetName, JSONData, PNGSheets); - } - - public function SetData(assetName = "", JSONData = null, PNGSheets = null) - { - this.AssetName = assetName; - this.JSONData = JSONData; - this.PNGSheets = PNGSheets; - } - - - - - - } - -} diff --git a/Job.as b/Job.as deleted file mode 100755 index c8d76f5..0000000 --- a/Job.as +++ /dev/null @@ -1,155 +0,0 @@ -package -{ - import flash.utils.*; - import flash.geom.*; - import flash.display.*; - import com.adobe.images.PNGEncoderWithAlpha; - public class Job - { - private var callback; - - private var id:int; - private var name:String; - - private var details; - - private var graphics:Array = new Array(); - - public function GetID():int { return this.id; } - public function Job(id:int, graphicsDetails:Array) - { - this.id = id; - for (var i in graphicsDetails) - { - var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); - if (graphic.valid) - { - graphics.push(graphic); - } - } - Exporter.Instance.Trace("new job: " + id); - } - public function FailMessage(err:String) - { - Exporter.Instance.Print("Failure: job " + id + ": " + err); - } - - public function WarnMessage(err:String) - { - Exporter.Instance.Print("Warning: job " + id + ": " + err); - } - - private function Fail(err:String) - { - FailMessage(err); - callback(); - } - - private var goIndex = -1; - public function Go(callback) - { - this.callback = callback; - - goIndex = -1; - - CheckNextGraphic(); - } - - private function CheckNextGraphic() - { - goIndex++; - if (goIndex < graphics.length) - { - graphics[goIndex].Go(CheckNextGraphic); - } - else - { - Pack(); - } - } - - private var allFrames:Array; //[FrameInfo] - private var packer:FramePacker; - private function Pack() - { - allFrames = new Array(); - for (var i in graphics) - { - if (graphics[i].valid) - { - allFrames = allFrames.concat(graphics[i].GetFrames()); - } - } - packer = new FramePacker(allFrames); - packer.Pack(PackDone); - } - - private var sheets:Array; //[BitmapData] - private var sheetBytes:Array; //[ByteArray] - - private function PackDone(success) - { - if (!success) - { - Fail("couldn't pack exported frames to sheets"); - return; - } - - var i; - var sheet:BitmapData; - - sheets = new Array(); - sheetBytes = new Array(); - var sheetAllocators:Array = packer.GetSheets(); - for (i in sheetAllocators) - { - var allocator:RectanglePacker = sheetAllocators[i]; - sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); - sheets.push(sheet); - } - for (i in allFrames) - { - var frame:FrameInfo = allFrames[i]; - sheet = sheets[frame.sheetIndex]; - sheet.copyPixels(frame.frame, frame.frame.rect, frame.rect.topLeft); - } - for (i in sheets) - { - sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); - } - - Done(); - } - - public function Done() - { - Exporter.Instance.Trace("Job.Done() " + id); - this.callback(); - } - - public function GetResources():Array //[ByteArray] - { - return sheetBytes; - } - - public function GetData() - { - var ret = {}; - for (var i in graphics) - { - if (graphics[i].valid) - { - if (ret[graphics[i].name] !== undefined) - { - WarnMessage("two graphics with same name: " + graphics[i].name); - } - else - { - ret[graphics[i].name] = graphics[i].GetData(); - } - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Packer/AsyncGraphicPacker.as b/Packer/AsyncGraphicPacker.as deleted file mode 100644 index ae68d5c..0000000 --- a/Packer/AsyncGraphicPacker.as +++ /dev/null @@ -1,1039 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - import djarts.utils.SimpleTimer; - - import flash.events.*; - - import djarts.core.*; - import djarts.display.*; - - public class AsyncGraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - public var ExpandSpriteRegionEdgeAlphas = true; - - public var outputFormat = "binary"; - public var outputAssetName = ""; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam, outputFormat = "binary") - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - this.outputFormat = outputFormat; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array, callback) - { - this.doneCallback = callback; - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - this.Export(false); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save=true, callback=null) - { - this.doneCallback = callback; - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - public function GetOutput(){return output;} - - var jsonPngSet:JSONPNGSet; - public function GetJSONPNGSet(){ return jsonPngSet; } - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - var output:ByteArray = new ByteArray(); - var sorted:Array; - var saveExport = false; - public function Export(save = true) - { - sheetIndex = 0; - clipIndex = 0; - this.saveExport = save; - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - sorted = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - output = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - DrawClipsToSheets(); - } - - var clipIndex = 0; - function DrawClipsToSheets() - { - - var perPass = 5; - var start = clipIndex; - for (var i = start; i < clips.length && i <= start + perPass; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - clipIndex++; - } - - if (clipIndex == clips.length) - { - DrawFontsToSheets(); - EncodeToPNGAndWriteSheetsToOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, DrawClipsToSheets); - } - - } - - function DrawFontsToSheets() - { - /* Do all the Fonts at once, they are not slow.. */ - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - } - - var sheetIndex = 0; - var pngSheets:Array; - function EncodeToPNGAndWriteSheetsToOutput() - { - - if (sheetIndex == 0) - { - output.writeUnsignedInt(sheets.length); - } - - pngSheets = new Array(); - - var perPass = 5; - var start = sheetIndex; - for (var i = start; i < sheets.length && i <= start + perPass; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - if (ExpandSpriteRegionEdgeAlphas) ExpandSpriteSheetEdgeAlpha(s); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - pngSheets.push(png); - _strace("PNG Processed Sheet "+i+" of " + sheets.length); - sheetIndex++; - } - - if (sheetIndex == sheets.length) - { - WriteSpriteInfoAndCompleteOutput(); - } else { - var t:SimpleTimer = new SimpleTimer(0.001, EncodeToPNGAndWriteSheetsToOutput); - } - } - - var jsonOutput; - function WriteSpriteInfoAndCompleteOutput() - { - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - var spriteNames = []; - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - - spriteNames.push(clipName); - - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - //Create JSON output for JSON Save - var jsonSpriteData = {}; - jsonSpriteData.format = "spritesheet"; - jsonSpriteData.graphics = []; - for (var i = 0; i < sprites.length; i++) - { - var spriteData = {}; - spriteData.name = spriteNames[i]; - - var tex:TextureSprite = sprites[i]; - spriteData.sequences = []; - for (var j = 0; j < tex.NumSequences(); j++) - { - var seq = []; - var info:SequenceInfo = tex.GetSequenceInfo(j); - for (var k = 0; k < info.Length; k++) - { - var frame = {}; - frame.texture = sheets.indexOf(info.FrameTextures[k]); - var location:Rectangle = info.FrameNodes[k].Rect; - frame.tx = location.x + PAD; - frame.ty = location.y + PAD; - frame.tw = location.width - (PAD * 2); - frame.th = location.height - (PAD * 2); - - var offset:Point = info.FrameOffsets[k]; - frame.x = offset.x - PAD; - frame.y = offset.y - PAD; - seq.push(frame); - } - spriteData.sequences.push(seq); - } - jsonSpriteData.graphics.push(spriteData); - } - - - //Convert to Texture Packer format. - var texturePackerJSON = {}; - var texturePackerFrames = {}; - for(var i = 0; i < jsonSpriteData.length; i++) - { - var spriteData = jsonSpriteData[i]; - var seqs = spriteData.sequences; - for (var j = 0; j < seqs.length; j++) - { - var seq = seqs[j]; - for (var k = 0; k < seq.length; k++) - { - var frame = {}; - frame.filename = (seqs.length == 1 && seq.length == 1) ? spriteData.name : spriteData.name+"_"+j+"_"+k; - frame.frame = {x:seq[k].tx,y:seq[k].ty,w:seq[k].tw,h:seq[k].th}; - frame.rotated = false; - frame.trimmed = false; - frame.spriteSourceSize = {x:0,y:0,w:seq[k].tw,h:seq[k].th}; - frame.sourceSize = {w:seq[k].tw,h:seq[k].th}; - frame.pivot = {x:seq[k].x/seq[k].tw,y:seq[k].y/seq[k].th}; - texturePackerFrames[frame.filename] = frame;//.push(frame); - } - } - } - texturePackerJSON.meta = {image:spriteNames[0]+".png"}; - texturePackerJSON.frames = texturePackerFrames; - - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (saveExport && outputFormat == "binary") - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - if (outputFormat == "json_png_set") - { - var assetName = (outputAssetName == "") ? spriteNames[0] : outputAssetName; - jsonPngSet = new JSONPNGSet(assetName, jsonSpriteData, pngSheets); - } - - if (this.doneCallback != null && callbackParam == null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet); - if (this.doneCallback != null && callbackParam != null) this.doneCallback(outputFormat == "binary" ? output : jsonPngSet, callbackParam); - } - - /* - public function SaveAsFileBundle() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, "sheet.json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngSheets.length > 0) - { - var pngSheet = pngSheets.shift(); - var fr:FileReference = new FileReference(); - fr.save(pngSheet, "sheet_.png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - }*/ - - /* This function expands the edges of the sprite rects. - This is important to prevent alpha bleeding when half pixels are sampled in engine */ - public function ExpandSpriteSheetEdgeAlpha(s:SpriteSheet) - { - var bitmap:BitmapData = s.GetBitmap(); - bitmap.lock(); - var nodes = s.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - var rect:Rectangle = nodes[n].Rect; - - var padding = PAD; - //top & bottom - for (var i = 0; i < 2; i++) - { - var y = rect.y + padding; - if (i == 1) y = rect.y + rect.height - padding - 1; - - var ySetOffset = i == 0 ? -1 : 1; - - for (var x = rect.x; x < rect.x + rect.width; x++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - - bitmap.setPixel32(x, y + ySetOffset, val); - if (a == 255) - { - bitmap.setPixel32(x, y + ySetOffset, (0xFF << 24) | rgb); - } - } - } - - //left & right - for (var i = 0; i < 2; i++) - { - var x = rect.x + padding; - if (i == 1) x = rect.x + rect.width - padding - 1; - - var xSetOffset = i == 0 ? -1 : 1; - - for (var y = rect.y; y < rect.y + rect.height; y++) - { - var val:uint = bitmap.getPixel32(x, y); - var a:uint = (val & 0xFF000000) >>> 24; - var rgb:uint = (val & 0xFFFFFF); - bitmap.setPixel32(x + xSetOffset, y, val); - if (a == 255) - { - bitmap.setPixel32(x + xSetOffset, y, (0xFF << 24) | rgb); - } - } - } - - } - - bitmap.unlock(); - } - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - var max = 0; - for (var i in clips) - { - if (clips[i].width > max) max = clips[i].width; - if (clips[i].height > max) max = clips[i].height; - - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - var exponent = Math.ceil(Math.log(max) / Math.log(2)); - max = Math.pow(2, exponent); - - //rough heuristic to see if this process is worth doing. - //it can be slow if there are a large number of big clips. - if (clips.length > 100 && max >= 512) - { - var s = Math.max(max, 1024); - return new Point(s, s); - } - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/BitmapFont.as b/Packer/BitmapFont.as deleted file mode 100644 index e6c5fc2..0000000 --- a/Packer/BitmapFont.as +++ /dev/null @@ -1,246 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - import djarts.core.*; - - - public class BitmapFont - { - public var CodepointData:Array = new Array(); - public var IndexByCodepoint = {}; - - public var Name = ""; - public var Size; - public var Bold; - - public var AsBackupOnly = false; - - private var backupFont:BitmapFont = null; - private var useBackupCodepoints = {}; - - private var useDeviceFontIfNeccessary = true; - - private var fontFaceName; - - public function BitmapFont(font:String, size:int, bold, backupFont:BitmapFont = null, useBackupCodepoints:String = null, asBackupOnly = false, useDeviceFontIfNeccessary = true) - { - this.fontFaceName = font; - this.Name = font + size + (bold ? "Bold" : ""); - this.Size = size; - this.Bold = bold; - - this.backupFont = backupFont; - if (useBackupCodepoints != null) - { - for (var i = 0; i < useBackupCodepoints.length; i++) - { - this.useBackupCodepoints[useBackupCodepoints.charCodeAt(i)] = true; - } - } - - this.useDeviceFontIfNeccessary = useDeviceFontIfNeccessary; - - this.AsBackupOnly = asBackupOnly; - - var additionalChars = ""; - /* - for (var i = 1024; i < 1280; i++) - { - additionalChars += String.fromCharCode(i); - } - */ - CreateFrames(font, size, bold, additionalChars /*"侧"*/); - } - - private function AddCodepoint(data:FontCodepointData) - { - IndexByCodepoint[data.Codepoint] = CodepointData.length; - CodepointData.push(data); - } - - private var lineHeight = 10; - - public function CreateFrames(font:String, size:int, bold, additionalCodepoints:String) - { - var base:String = ""; - for (var i = 32; i < 256; i++) - { - base += String.fromCharCode(i); - } - var text:String = base + additionalCodepoints; - - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.font = font; - f.color = 0xFFFFFF; - f.size = size; - f.bold = bold; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - t.embedFonts = true; - t.antiAliasType = AntiAliasType.ADVANCED; - - var tDevice:TextField = new TextField(); - tDevice.type = TextFieldType.DYNAMIC; - tDevice.defaultTextFormat = f; - tDevice.selectable = false; - tDevice.autoSize = TextFieldAutoSize.LEFT; - tDevice.embedFonts = false; - tDevice.antiAliasType = AntiAliasType.ADVANCED; - - t.text = "Test"; - var testMetrics:TextLineMetrics = t.getLineMetrics(0); - lineHeight = testMetrics.height; - - for (var i = 0; i < text.length; i++) - { - var codepointStr = text.charAt(i); - var codepoint = text.charCodeAt(i); - - - var field:TextField = t; - - field.text = codepointStr; - - var lm:TextLineMetrics = t.getLineMetrics(0); - if ((lm.width == 0 && codepoint != 32) || this.useBackupCodepoints[codepoint]) - { - // not sure we need this recursive search, actually - var searchFont = this; - var found = false; - while (searchFont != null) - { - if (searchFont.backupFont != null && searchFont.backupFont.IndexByCodepoint[codepoint] != undefined) - { - // use the backup font's frame - var index = searchFont.backupFont.IndexByCodepoint[codepoint]; - - if (searchFont.backupFont.CodepointData[index] && searchFont.backupFont.CodepointData[index].CodepointWidth != 0) - { - var data:FontCodepointData = new FontCodepointData(codepoint); - data.InitFromOtherFont(searchFont.backupFont, index); - - AddCodepoint(data); - - searchFont.backupFont.CodepointData[searchFont.backupFont.IndexByCodepoint[codepoint]].References++; - - found = true; - break; - } - } - break; - //searchFont = searchFont.backupFont; - } - - if (found) continue; - - if (this.useBackupCodepoints[codepoint]) - { - // back up font didn't have this character, so skip - continue; - } - if (this.useDeviceFontIfNeccessary) - { - field = tDevice; - - tDevice.text = codepointStr; - lm = tDevice.getLineMetrics(0); - } - } - - var bounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - bounds.left = Math.floor(bounds.left); - bounds.right = Math.ceil(bounds.right); - bounds.top = Math.floor(bounds.top); - bounds.bottom = Math.ceil(bounds.bottom); - - if ((bounds.width == 0 || bounds.height == 0) && codepoint != 32) continue; - - var offsetX = 0; - var offsetY = 0; - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size + 25; - field.defaultTextFormat = tf; - // is this neccessary to refresh the size??? - field.text = field.text; - - var newBounds:Rectangle = CacheManager.Instance().GetAccurateBounds(field); - newBounds.left = Math.floor(newBounds.left); - newBounds.right = Math.ceil(newBounds.right); - newBounds.top = Math.floor(newBounds.top); - newBounds.bottom = Math.ceil(newBounds.bottom); - - offsetY -= (newBounds.bottom - bounds.bottom); - bounds.left = newBounds.left; - bounds.right = newBounds.right; - bounds.top = Math.min(bounds.top, newBounds.top + offsetY); - - lm = t.getLineMetrics(0); - } - - if (fontFaceName == "Grobold" && (codepointStr == "!" || codepointStr == "%")) - { - var adjust = Math.floor(bounds.left * 0.7); - bounds.x -= adjust; - offsetX -= adjust; - } - - var bitmapData:BitmapData = new BitmapData(bounds.width + GraphicPacker.PAD * 2, bounds.height + GraphicPacker.PAD * 2, true, 0x00000000); - bitmapData.draw(field, new Matrix(1, 0, 0, 1, -bounds.left + GraphicPacker.PAD + offsetX, -bounds.top + GraphicPacker.PAD + offsetY)); - - var data:FontCodepointData = new FontCodepointData(codepoint); - var offset:Point = new Point(-bounds.left + GraphicPacker.PAD, -bounds.top + GraphicPacker.PAD); - - var codepointWidth = Math.ceil(lm.width); - if (lm.width > bounds.width && bounds.width != 0) - { - codepointWidth = bounds.width; - } - data.Init(bitmapData, offset, codepointWidth); - - AddCodepoint(data); - - if (fontFaceName == "Grobold" && codepointStr == ".") - { - var tf:TextFormat = field.defaultTextFormat; - tf.size = size; - field.defaultTextFormat = tf; - } - } - } - - public function GetAdditionalData() - { - var codepoints:Array = new Array(); - var advances:Array = new Array(); // the width of the character (not the character graphic) is called advance in the client - for (var i = 0; i < CodepointData.length; i++) - { - codepoints.push(CodepointData[i].Codepoint); - advances.push(CodepointData[i].CodepointWidth); - } - - - return {"codepoints":codepoints,"advances":advances,"line_height":lineHeight}; - } - - - } - -} diff --git a/Packer/BitmapFontCopy.as b/Packer/BitmapFontCopy.as deleted file mode 100644 index 478d546..0000000 --- a/Packer/BitmapFontCopy.as +++ /dev/null @@ -1,39 +0,0 @@ -package Packer { - - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.geom.*; - import flash.display.MovieClip; - import flash.text.AntiAliasType; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.text.TextLineMetrics; - - - - public class BitmapFontCopy { - - public var Name = ""; - public var Other:BitmapFont; - - public function BitmapFontCopy(font:String, size:String, bold, other:BitmapFont) - { - this.Other = other; - Name = font+""+size; - if (bold) Name = Name+"Bold"; - } - - public function GetAdditionalData() - { - return Other.GetAdditionalData(); - } - - - } - -} diff --git a/Packer/FontCodepointData.as b/Packer/FontCodepointData.as deleted file mode 100644 index 3b360d3..0000000 --- a/Packer/FontCodepointData.as +++ /dev/null @@ -1,50 +0,0 @@ -package Packer -{ - import flash.display.*; - import flash.geom.*; - - public class FontCodepointData - { - public var Codepoint; - - public var DestinationNode:RectangleNode = null; - public var References = 0; - - public var Offset:Point = new Point(); - - public var CodepointWidth = 0; - - public var FromOtherFont = false; - - // comes from another font - public var FromFont:BitmapFont; - public var FromFontIndex = 0; - - // comes from this font - public var Data:BitmapData = null; - - public function FontCodepointData(codepoint) - { - this.Codepoint = codepoint; - } - - public function InitFromOtherFont(fromFont:BitmapFont, index) - { - this.FromOtherFont = true; - this.FromFont = fromFont; - this.FromFontIndex = index; - - var otherData:FontCodepointData = fromFont.CodepointData[index]; - this.CodepointWidth = otherData.CodepointWidth; - this.Offset = otherData.Offset; - } - - public function Init(data:BitmapData, offset:Point, codepointWidth) - { - this.FromOtherFont = false; - this.Data = data; - this.Offset = offset; - this.CodepointWidth = codepointWidth; - } - } -} \ No newline at end of file diff --git a/Packer/GraphicDefClipCollection.as b/Packer/GraphicDefClipCollection.as deleted file mode 100644 index 00c9906..0000000 --- a/Packer/GraphicDefClipCollection.as +++ /dev/null @@ -1,54 +0,0 @@ -package Packer { - - import djarts.core.CacheManager; - import djarts.core.*; - import djarts.display.*; - - public class GraphicDefClipCollection - { - - public var ClipsLoaded = null; - public function GraphicDefClipCollection(graphicDefs:Array = null, callback = null) - { - if (graphicDefs != null) LoadDefs(graphicDefs, callback); - } - - var defs = null; - public function LoadDefs(graphicDefs:Array, callback) - { - defs = graphicDefs; - ClipsLoaded = callback; - LoadNextDef(); - } - - public function LoadNextDef() - { - if (defs.length == 0) - { - Done(); - return; - } - - var currentDef = defs.shift(); - var g = GraphicFactory.Instance().GetGraphicByID(currentDef.ID, null, GraphicLoaded); - if (GraphicFactory.Instance().LoadedOK(g)) - { - GraphicLoaded(null, g); - } - } - - var clips = new Array(); - protected function GraphicLoaded(caller, g) - { - clips.push(g); - LoadNextDef(); - } - - protected function Done() - { - if (ClipsLoaded != null) ClipsLoaded(clips); - } - - } - -} diff --git a/Packer/GraphicPacker.as b/Packer/GraphicPacker.as deleted file mode 100644 index dbaf85b..0000000 --- a/Packer/GraphicPacker.as +++ /dev/null @@ -1,807 +0,0 @@ -package Packer -{ - import flash.display.MovieClip; - import flash.display.Stage; - import flash.geom.*; - import flash.display.*; - import flash.utils.ByteArray; - import flash.utils.getQualifiedClassName; - import flash.net.FileReference; - import flash.utils.Endian; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import flash.utils.*; - - import djarts.core.CacheManager; - import com.adobe.serialization.json.JSON; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import fl.motion.AdjustColor; - - import djarts.core.*; - import djarts.display.*; - - public class GraphicPacker - { - protected var clips:Array = new Array(); - protected var clipSizing:Array = new Array(); - protected var fonts:Array = new Array(); - protected var fontCopies:Array = new Array(); - protected var sheetWidth = 1024; - protected var sheetHeight = 1024; - protected var stage; - - protected var additionalData = {}; - public var regionsOutput = new MovieClip(); - - public function Init(sheetWidth, sheetHeight, stage) - { - this.sheetWidth = sheetWidth; - this.sheetHeight = sheetHeight; - this.stage = stage; - } - - protected var doneCallback = null; - protected var callbackParam; - public function ExportDefs(graphicDefs:Array, callback, callbackParam) - { - this.doneCallback = callback; - this.callbackParam = callbackParam; - var clipCollection:GraphicDefClipCollection = new GraphicDefClipCollection(graphicDefs, GraphicDefsLoaded); - } - - public function ExportClips(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - return this.Export(false); - } - - public function GraphicDefsLoaded(clips:Array) - { - this.clips = clips; - var sheetSize:Point = this.DetermineMinimumSheetSizeForClips(); - this.sheetWidth = sheetSize.x; - this.sheetHeight = sheetSize.y; - var output:ByteArray = this.Export(false); - this.doneCallback(output, callbackParam); - } - - public function AddClip(clip:MovieClip, scale=1, sizing:Point = null) - { - clip.scaleX = clip.scaleX * scale; - clip.scaleY = clip.scaleY * scale; - clips.push(clip); - clipSizing.push(sizing); - } - - public function AddBitmapFont(font:BitmapFont) - { - fonts.push(font); - } - - public function AddBitmapFontCopy(font:BitmapFont, toName:String) - { - fontCopies.push({from:font,to:toName}); - } - - protected var sheet = 0; - public function ExportFrom(clip, scale=1, save = true) - { - - for (var i = 0; i < clip.numChildren; i++) - { - if (clip.getChildAt(i) is MovieClip) - { - AddClip(clip.getChildAt(i), scale); - } - } - return Export(save); - } - - public static const CACHESEQUENCES = 0; - public static const PAD = 2; - - public function GetSheets(){return sheets;} - - public var sheets:Array = new Array(); - protected var sprites:Array = new Array(); - protected var spriteOriginalClips:Array = new Array(); - public function Export(save = true) - { - additionalData = {}; - sheets = new Array(); - sprites = new Array(); - spriteOriginalClips = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(sheetWidth, sheetHeight)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - spriteOriginalClips.push(clips[sorted[i]]); - _strace("cached clip "+i+" of "+clips.length); - } - - var fontSpritesByName = {}; - for (var i in fonts) - { - var sprite:TextureSprite = new TextureSprite(fonts[i], CACHESEQUENCES); - CopyBitmapFontToSingleSheet(fonts[i], sprite); - sprites.push(sprite); - spriteOriginalClips.push(fonts[i]); - additionalData[fonts[i].Name] = fonts[i].GetAdditionalData(); - fontSpritesByName[fonts[i].Name] = sprite; - } - - for (var i in fontCopies) - { - var f:BitmapFontCopy = new BitmapFontCopy(fontCopies[i].to, fontCopies[i].from.Size, fontCopies[i].from.Bold, fontCopies[i].from); - sprites.push(fontSpritesByName[fontCopies[i].from.Name]); - spriteOriginalClips.push(f); - additionalData[f.Name] = f.GetAdditionalData(); - } - - - var output:ByteArray = new ByteArray(); - output.endian = Endian.LITTLE_ENDIAN; - - output.writeUnsignedInt(sheets.length); - for (var i = 0; i < sheets.length; i++) - { - var s:SpriteSheet = sheets[i]; - output.writeUnsignedInt(s.width); - output.writeUnsignedInt(s.height); - var png:ByteArray = PNGExportHelper.GetExportPNG(s.GetBitmap()); - output.writeUnsignedInt(png.length); - output.writeBytes(png); - } - - for (var i = 0; i < sprites.length; i++) - { - var orig = spriteOriginalClips[i]; - if (orig is BitmapFont && orig.AsBackupOnly) - { - sprites.splice(i, 1); - spriteOriginalClips.splice(i, 1); - i--; - } - } - - output.writeUnsignedInt(sprites.length); - for (var i = 0; i < sprites.length; i++) - { - var tex:TextureSprite = sprites[i]; - var orig = spriteOriginalClips[i]; - var clipName = "clip"; - if (orig is BitmapFont || orig is BitmapFontCopy) - { - clipName = orig.Name; - } else { - clipName = getQualifiedClassName(orig); - if (clipName == "flash.display::MovieClip") - { - clipName = orig.name; - } - } - _strace("Exporting "+clipName); - output.writeUnsignedInt(clipName.length); - output.writeMultiByte(clipName, "us-ascii"); - output.writeUnsignedInt(tex.NumSequences()); - for (var j = 0; j < tex.NumSequences(); j++) - { - var info:SequenceInfo = tex.GetSequenceInfo(j); - output.writeUnsignedInt(info.Length); - _strace("With "+info.Length+" Frames"); - for (var k = 0; k < info.Length; k++) - { - output.writeUnsignedInt(sheets.indexOf(info.FrameTextures[k])); - var location:Rectangle = info.FrameNodes[k].Rect; - output.writeFloat(location.x + PAD); - output.writeFloat(location.y + PAD); - output.writeFloat(location.width - (PAD * 2)); - output.writeFloat(location.height - (PAD * 2)); - var offset:Point = info.FrameOffsets[k]; - output.writeFloat(offset.x - PAD); - output.writeFloat(offset.y - PAD); - - regionsOutput.graphics.beginFill(0x00CCFF, .2); - regionsOutput.graphics.lineStyle(1, 0x00CCFF); - regionsOutput.graphics.drawRect(location.x + PAD, location.y + PAD, location.width - (PAD * 2), location.height - (PAD * 2)); - regionsOutput.graphics.endFill(); - } - } - } - - var additionalDataString = com.adobe.serialization.json.JSON.encode(additionalData); - output.writeUnsignedInt(additionalDataString.length); - output.writeMultiByte(additionalDataString, "us-ascii"); - - if (save) - { - var fr:FileReference = new FileReference(); - fr.save(output, "data.pak"); - } - _strace("done. num sheets: " + sheets.length); - - return output; - } - - - public function DetermineMinimumSheetSizeForClips():Point - { - - /* TODO - FOR LARGE SIZED CHUNKS BETTER HANDLING FOR FINDING MINIMUM SIZE! */ - - sheets = new Array(); - sprites = new Array(); - - var areas:Array = new Array(); - for (var i in clips) - { - areas[i] = clips[i].width * clips[i].height; - } - var sorted:Array = areas.sort(Array.RETURNINDEXEDARRAY | Array.NUMERIC | Array.DESCENDING); - - sheets.push(new SpriteSheet(2048, 2048)); - for (var i = 0; i < clips.length; i++) - { - var sprite:TextureSprite = new TextureSprite(clips[sorted[i]], CACHESEQUENCES); - CacheClip(clips[sorted[i]], sprite); - sprites.push(sprite); - } - - var allUsedRects:Array = new Array(); - var nodesToVisit:Array = new Array(); - for (var i = 0; i < sheets.length; i++) - { - var sheet:SpriteSheet = sheets[i]; - var nodes = sheet.GetAllocator().GetLeafNodes(); - for (var n = 0; n < nodes.length; n++) - { - allUsedRects.push(nodes[n].Rect); - } - } - - var sizeFound = false; - var sheetSizeX = 64; - var sheetSizeY = 64; - while(!sizeFound) - { - var sheet:SpriteSheet = new SpriteSheet(sheetSizeX, sheetSizeY); - sizeFound = true; - for(var i = 0; i < allUsedRects.length; i++) - { - var node:RectangleNode = sheet.GetAllocator().Insert(allUsedRects[i].width, allUsedRects[i].height); - if (node == null) - { - sizeFound = false; - break; - } - } - if (sizeFound == false) - { - if (sheetSizeX == sheetSizeY) - { - sheetSizeX *= 2; - } - else - { - sheetSizeY *= 2; - } - } - } - return new Point(sheetSizeX, sheetSizeY); - } - - - protected function CopyBitmapFontToSingleSheet(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - // track the nodes we have locally created, if we can't fit - // everything on 1 sheet we will remove them - var createdNodes:Array = new Array(); - - var createdNewSheet = false; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var ok = true; - - for (var i = 0; i < font.CodepointData.length; i++) - { - var node:RectangleNode = null; - - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - } - else if (data.FromOtherFont) - { - // this is a copy node, from a backup font - node = data.FromFont.CodepointData[data.FromFontIndex].DestinationNode; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - // failed to fit the entire font on a sheet, so let's clear - // everything and start again - ok = false; - - for (var j in createdNodes) - { - sheet.GetBitmap().fillRect(createdNodes[j].Rect, 0x0); - } - - sheet.GetAllocator().RemoveNodes(createdNodes, false); - nodes = new Array(); - createdNodes = new Array(); - - break; - } - createdNodes.push(node); - } - - nodes.push(node); - } - if (ok) - { - // the nodes array is completed (length == font.CodepointData.length) - // now we have to setup the sheet indices, bounds, offsets, etc... - for (var i = 0; i < font.CodepointData.length; i++) - { - var data:FontCodepointData = font.CodepointData[i]; - if (font.AsBackupOnly && data.References == 0) - { - // do nothing - offsets.push(new Point()); - bounds.push(new Rectangle()); - localSheets.push(-1); - } - else - { - var node:RectangleNode = nodes[i]; - - if (!data.FromOtherFont) - { - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - offsets.push(data.Offset); - bounds.push(node.Rect.clone()); - - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - } - } - break; - } - else - { - if (s == sheets.length - 1) - { - if (createdNewSheet) - { - // couldn't fit the font on 1 sheet - CopyBitmapFontToSheets(font, sprite); - return; - } - else - { - createdNewSheet = true; - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - } - } - } - } - } - - for (var j = 0; j < nodes.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - protected function CopyBitmapFontToSheets(font:BitmapFont, sprite:TextureSprite) - { - sprite.SetSequence(0, font.CodepointData.length); - - // info to go into the sprite - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - - var i = 0; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - var sheetIndex = useSheets.length - 1; - - var searchBackwards = true; - - var done = false; - - while (!done) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - - if (!sheet.sheetFull) - { - var count = 0; - var spaceAvailable = true; - - while (spaceAvailable && i < font.CodepointData.length) - { - var data:FontCodepointData = font.CodepointData[i]; - - var node:RectangleNode = null; - var offset:Point = new Point(); - - if (font.AsBackupOnly && data.References == 0) - { - // do nothing, this sprite won't be used ever - } - else if (data.FromOtherFont) - { - var copyData:FontCodepointData = data.FromFont.CodepointData[data.FromFontIndex]; - node = copyData.DestinationNode; - offset = copyData.Offset; - } - else - { - node = sheet.GetAllocator().Insert(data.Data.width, data.Data.height); - if (node == null) - { - spaceAvailable = false; - break; - } - - offset = data.Offset; - - sheet.GetBitmap().copyPixels(data.Data, data.Data.rect, new Point(node.Rect.x, node.Rect.y), null, null, true); - } - - nodes.push(node); - offsets.push(offset); - bounds.push(node.Rect.clone()); - localSheets.push(node.Host.HostTexture); - - data.DestinationNode = node; - - i++; - count++; - } - /* - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - */ - - if (i < font.CodepointData.length) - { - if (searchBackwards) - { - sheetIndex--; - if (sheetIndex < 0) - { - searchBackwards = false; - sheetIndex = sheets.length - 1; - } - } - if (!searchBackwards) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - sheetIndex++; - } - } - else - { - done = true; - } - } - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(0, j, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - - sprite.Loaded = true; - } - - public static var UseFlatHeuristic = false; - private function AnalyzeClipType(clip:MovieClip):MovieClip - { - var isFlat = false; - - if (clip.totalFrames > 1 && UseFlatHeuristic) - { - var framesWithMultiChildren = 0; - var totalChildren = 0; - var childrenWithSingleFrame = 0; - for (var i = 0; i < clip.totalFrames; i++) - { - clip.gotoAndStop(i); - var children = clip.numChildren; - totalChildren += children; - if (children > 1) framesWithMultiChildren++; - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (!(child is MovieClip) || child.totalFrames == 1) - { - childrenWithSingleFrame++; - } - } - } - if (framesWithMultiChildren / clip.totalFrames > 0.75) - { - if (childrenWithSingleFrame / totalChildren > 0.75) - { - isFlat = true; - } - } - } - - if (isFlat) - { - var ret:MovieClip = new MovieClip(); - ret.addChild(clip); - return ret; - } - else - { - return clip; - } - } - - protected function CacheClip(clip:MovieClip, sprite:TextureSprite) - { - clip = AnalyzeClipType(clip); - - var totalFrames = clip.totalFrames; - - var startSeq = 1; - var endSeq = totalFrames; - - for (var i = startSeq; i <= endSeq; i++) - { - var endFrame = 1; - - RecursivelyStop(clip, i); - - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip) - { - if (child.totalFrames > endFrame) endFrame = child.totalFrames; - } - } - - var offsets:Array = new Array(); - var bounds:Array = new Array(); - var nodes:Array = new Array(); - var localSheets:Array = new Array(); - var completed = false; - var startFrame = 1; - - sprite.SetSequence(i - 1, endFrame); - - var origStart = startFrame; - - var useSheets:Array = new Array(); - for (var s = 0; s < this.sheets.length; s++) - { - useSheets.push(s); - } - - for (var sheetIndex = 0; sheetIndex < useSheets.length; sheetIndex++) - { - var s = useSheets[sheetIndex]; - var sheet:SpriteSheet = sheets[s]; - //if (this.ForceSpriteSheet) sheet = this.ForceSpriteSheet; - if (!sheet.sheetFull) - { - var count = 0; - count = CacheFrames(clip, offsets, bounds, sheet, nodes, startFrame, endFrame); - if (count > 0) - { - for (var q = 0; q < count; q++) - { - localSheets.push(sheet); - } - } - - startFrame += count; - - if (startFrame <= endFrame && s == sheets.length - 1) - { - var newSheet:SpriteSheet = new SpriteSheet(sheetWidth, sheetHeight); - newSheet.SheetIndex = sheets.length; - useSheets.push(sheets.length); - sheets.push(newSheet); - - } - } - } - - if (localSheets.length < endFrame - startFrame + 1) - { - _strace("GraphicPacker: Problem caching"); - } - - for (var j = 0; j < offsets.length; j++) - { - sprite.AddFrame(i - 1, j + origStart - 1, offsets[j], bounds[j], localSheets[j], nodes[j], null); - } - } - - sprite.Loaded = true; - } - - protected function CacheFrames(clip:MovieClip, offsets:Array, bounds:Array, sheet:SpriteSheet, nodes:Array, startFrame = 1, lastFrame = -1) - { - - if (lastFrame == -1) lastFrame = clip.totalFrames; - - for (var i = startFrame; i <= lastFrame; i++) - { - - SubclipsGotoFrame(clip, i, {}, clip); - RecursivelyStop(clip); - - var currentMatrix = clip.transform.matrix.clone(); - - var flippedX = currentMatrix.a < 0; - var flippedY = currentMatrix.d < 0; - var m:Matrix = new Matrix(currentMatrix.a, 0, 0, currentMatrix.d); - - var r:Rectangle = clip.getBounds(clip); - r = CacheManager.Instance().GetAccurateBounds(clip, 2048); - - var usedCacheBounds = false; - - if (clip.getChildByName("__cache_bounds__")) - { - usedCacheBounds = true; - r = clip.getChildByName("__cache_bounds__").getRect(clip); - clip.mask = clip.getChildByName("__cache_bounds__"); - } - - r.x *= Math.abs(m.a); - r.y *= Math.abs(m.d); - r.width *= Math.abs(m.a); - r.height *= Math.abs(m.d); - r.width += PAD * 2.0; - r.height += PAD * 2.0; - var w = Math.ceil(r.width); - var h = Math.ceil(r.height); - - - var node:RectangleNode = sheet.GetAllocator().Insert(w, h); - if (node == null) - { - return i - startFrame; - } - - nodes.push(node); - - var target:Point = new Point(node.Rect.x, node.Rect.y); - //flippedX = false; - var offsetX = flippedX ? Math.ceil(r.right - PAD * 2.0) : Math.ceil(-r.left); - var offsetY = flippedY ? Math.ceil(r.bottom - PAD * 2.0) : Math.ceil(-r.top); - - m.translate(offsetX + target.x + PAD, offsetY + target.y + PAD); - - var offset:Point = new Point(offsetX + PAD, offsetY + PAD); - - RenderBitmap(sheet, clip, m, new ColorTransform(1.0, 1.0, 1.0, clip.alpha)); - - offsets.push(offset); - bounds.push(node.Rect.clone()); - - if (usedCacheBounds) - { - clip.mask = null; - } - - } - - return lastFrame - startFrame + 1; - } - - protected function RenderBitmap(sheet:SpriteSheet, clip:MovieClip, m:Matrix, ct:ColorTransform) - { - sheet.GetBitmap().draw(clip, m, ct); - } - - protected function SubclipsGotoFrame(clip:MovieClip, i, force, rootClip, exceptClip = null) - { - - for (var j = 0; j < clip.numChildren; j++) - { - var child = clip.getChildAt(j); - if (child is MovieClip && child != exceptClip) - { - if (i != null) child.gotoAndStop(((i - 1) % child.totalFrames) + 1); - SubclipsGotoFrame(child, i, force, rootClip); - } - } - } - protected function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - - } -} \ No newline at end of file diff --git a/Packer/JSONPNGSetSaver.as b/Packer/JSONPNGSetSaver.as deleted file mode 100644 index b91690f..0000000 --- a/Packer/JSONPNGSetSaver.as +++ /dev/null @@ -1,41 +0,0 @@ -package GraphicExport -{ - public class JSONPNGSetSaver { - - var name:String; - var json:String; - var pngs:Array; - var sheetCount = 0; - var doneCallback:Function = null; - public function JSONPNGSetSaver(name:String, json:String, pngs:Array, callback:Function) - { - this.name = name; - this.json = json; - this.pngs = pngs; - doneCallback = callback; - } - - public function Save() - { - var fr:FileReference = new FileReference(); - fr.save(jsonOutput, this.name+".json"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } - - public function OutputNextFile(e:Event) - { - if (pngs.length > 0) - { - var pngSheet = pngs.shift(); - sheetCount++; - var fr:FileReference = new FileReference(); - fr.save(pngSheet, this.name+"_"+(sheetCount < 10) ? "0" : "")+sheetCount+".png"); - fr.addEventListener(Event.COMPLETE, OutputNextFile); - } else { - doneCallback(); - } - } - - } - -} diff --git a/Piece.as b/Piece.as deleted file mode 100644 index aea2f74..0000000 --- a/Piece.as +++ /dev/null @@ -1,175 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - - public class Piece - { - protected var size:Point; - protected var frame:FrameInfo; - protected var compareData:BitmapData; - - protected var centerPoint:Point; - public function get CenterPoint():Point { return centerPoint; } - - public function get FullData():BitmapData { return frame == null ? null : frame.frame; } - - public function get Frame():FrameInfo { return frame; } - - protected var valid = false; - public function get Valid() { return valid; } - - public var Name:String = null; - - protected var usesBySequence = {}; - public function AddUse(sequence) - { - if (!(sequence in usesBySequence)) - { - usesBySequence[sequence] = 0; - } - usesBySequence[sequence]++; - } - - public function RemoveUse(sequence) - { - if (sequence in usesBySequence && usesBySequence[sequence] > 0) - { - usesBySequence[sequence]--; - } - } - - public function GetUses(sequence) - { - return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; - } - - public function get TotalUses() - { - var count = 0; - for (var s in usesBySequence) - { - count += usesBySequence[s]; - } - return count; - } - - // returns the center point - public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point - { - var bounds:Rectangle = Utils.GetAccurateBounds(clip); - - size = new Point(bounds.width, bounds.height); - - valid = bounds.width > 0 && bounds.height > 0; - if (valid) - { - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(upscale, upscale); - - Utils.TransformRect(bounds, m); - Utils.RoundRect(bounds); - - m.translate(-bounds.left, -bounds.top); - - var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); - fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - frame = new FrameInfo(fullData, m, null); - - compareData = GenerateCompareData(clip); - - centerPoint = new Point(-bounds.left, -bounds.top); - return centerPoint; - } - return null; - } - - public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - valid = true; - size = new Point(bd.width, bd.height); - - frame = new FrameInfo(bd, null, null); - - compareData = bd.clone(); - - this.centerPoint = centerPoint; - } - - public function Matches(otherData:BitmapData, otherName) - { - - if (false && otherName != null && Name != null) - { - //This whole section fails to match things properly... - - var m = Name.match("^([^0-9]+)(\\d*)"); - var tempName = m ? m[1] : Name; - - var mo = otherName.match("^([^0-9]+)(\\d*)"); - var tempOtherName = mo ? mo[1] : otherName; - - return tempName == tempOtherName; - - - if (m) - { - if (otherName != m[1]) return false; - return true; - } - else - { - if (otherName != Name) return false; - return true; - } - } - - var threshold = 3; - var maxPixels = 0; - var result = compareData.compare(otherData); - if (result == 0) return true; - if (result is BitmapData) - { - var histo:Vector.> = (result as BitmapData).histogram(); - for (var i = 0; i < 4; i++) - { - var diff:Vector. = histo[i]; - // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... - // so DON'T compare the histogram for color channels up to 255 - var max = i == 4 ? 255 : 254; - for (var j = threshold; j < Math.min(max, diff.length); j++) - { - if (diff[j] > maxPixels) - { - return false; - } - } - } - return true; - } - return false; - } - - public static function GenerateCompareData(clip:DisplayObject):BitmapData - { - var scale = 1; - - var quickBounds:Rectangle = clip.getBounds(clip); - var orig:Rectangle = quickBounds.clone(); - if (quickBounds.width == 0 || quickBounds.height == 0) return null; - Utils.ScaleRect(quickBounds, scale); - Utils.RoundRect(quickBounds); - - var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); - m.scale(scale, scale); - m.translate(-quickBounds.left, -quickBounds.top); - - var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); - data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); - - return data; - } - } -} \ No newline at end of file diff --git a/PieceFrameInfo.as b/PieceFrameInfo.as deleted file mode 100644 index a656f09..0000000 --- a/PieceFrameInfo.as +++ /dev/null @@ -1,10 +0,0 @@ -package -{ - import flash.geom.*; - public class PieceFrameInfo - { - public var Present = false; - public var Transform:Matrix = null; - public var Depth = null; - } -} \ No newline at end of file diff --git a/PieceLibrary.as b/PieceLibrary.as deleted file mode 100644 index e5745bd..0000000 --- a/PieceLibrary.as +++ /dev/null @@ -1,154 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.Point; - import flash.utils.*; - - public class PieceLibrary - { - protected var pieces:Array = []; - - public function Reset() - { - pieces.splice(0); - } - - private function GetArtistGivenName(clipName:String):String - { - if (clipName.match(/instance\d+/)) - { - return null; - } - return clipName; - } - - private function GetNextAvailableName(artistName:String):String - { - if (artistName == null) return null; - if (artistName.match("^instance\\d+$")) return null; - - var maxNameCount = 0; - for (var i in pieces) - { - if (pieces[i].Name != null) - { - var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); - if (m) - { - maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); - } - } - } - return artistName + (maxNameCount == 0 ? "" : maxNameCount); - } - - public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) - { - var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); - if (piece != null) return piece; - - piece = new Piece(); - var center:Point = piece.InitFromClip(clip, upscale); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(clip.name); - - pieces.push(piece); - outCenterPoint.x = center.x; - outCenterPoint.y = center.y; - return piece; - } - - return null; - } - - private function GetExistingPiece(compareData:BitmapData, artistName:String) - { - if (compareData == null) return null; - - for (var i in pieces) - { - if (pieces[i].Matches(compareData, artistName)) - { - if (pieces[i].Name == null) - { - pieces[i].Name = GetNextAvailableName(artistName); - } - return pieces[i]; - } - } - - return null; - } - - public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) - { - if (centerPoint == null) centerPoint = new Point(0, 0); - - var piece:Piece = GetExistingPiece(bd, pieceName); - if (piece != null) return piece; - - piece = new Piece(); - piece.InitFromBitmapData(bd, centerPoint); - if (piece.Valid) - { - piece.Name = GetNextAvailableName(pieceName); - pieces.push(piece); - return piece; - } - - return null; - } - - public function Debug() - { - var nextX = 0; - for (var i = 0; i < pieces.length; i++) - { - if (pieces[i].TotalUses > 0) - { - var b:Bitmap = new Bitmap(pieces[i].FullData); - b.scaleX = b.scaleY = 1; - b.x = nextX; - nextX += b.width; - } - } - } - - public function get NumUsedPieces() - { - var count = 0; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - count++; - } - } - return count; - } - - public function GetAllUsedPieces():Array - { - var ret:Array = []; - for (var i in this.pieces) - { - if (pieces[i].TotalUses > 0) - { - ret.push(pieces[i]); - } - } - return ret; - } - - public function EnsureAllUsedPiecesHaveNames() - { - var index = 0; - var used:Array = GetAllUsedPieces(); - for (var i in used) - { - if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); - } - } - } -} \ No newline at end of file diff --git a/PieceSequence.as b/PieceSequence.as deleted file mode 100644 index 64fde8e..0000000 --- a/PieceSequence.as +++ /dev/null @@ -1,62 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class PieceSequence - { - protected var piece:Piece; - protected var overridePiece:Piece; - public function GetOriginalPiece():Piece { return piece; } - public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } - public function SetOverridePiece(p:Piece) { this.overridePiece = p; } - - public var Export:Boolean = true; - - //protected var centerPoint:Point; - //public function get CenterPoint():Point { return centerPoint; } - - public function GetFrame(frame):PieceFrameInfo - { - if (frame < 1 || frame > frames.length) return null; - return frames[frame - 1]; - } - - public function CopyTransformsFrom(other:PieceSequence, atDepth = null) - { - if (other.frames.length == this.frames.length) - { - for (var i = 0; i < frames.length; i++) - { - this.frames[i].Present = other.frames[i].Present; - if (other.frames[i].Present) - { - this.frames[i].Transform = other.frames[i].Transform.clone(); - this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; - } - } - } - } - - protected var frames:Array = []; - public function PieceSequence(piece:Piece, length) //, centerPoint:Point) - { - this.piece = piece; - //this.centerPoint = centerPoint; - for (var i = 0; i < length; i++) - { - frames.push(new PieceFrameInfo()); - } - } - - // clip matching info - public var BaseClip:DisplayObject = null; - public var Name = null; - - public function CheckMatches(clip:DisplayObject) - { - if (BaseClip != null && clip == BaseClip) return true; - if (Name != null && clip.name == null) return true; - return false; - } - } -} \ No newline at end of file diff --git a/RectangleNode.as b/RectangleNode.as deleted file mode 100755 index a6b0c74..0000000 --- a/RectangleNode.as +++ /dev/null @@ -1,178 +0,0 @@ -package { - import flash.geom.Rectangle; - - public class RectangleNode - { - public var Left:RectangleNode = null; - public var Right:RectangleNode = null; - public var Rect:Rectangle = null; - public var InUse:Boolean = false; - public var Removed:Boolean = false; - public var Parent:RectangleNode = null; - public var AllocationID = 0; - public var Host:RectanglePacker= null; - public var MinAllocationID = 0; - public var NodeID; - public static var NextNodeID = 0; - - public var DontRemove = false; - - public var LastAccessTime = 0; - - public var Flags = []; - - public var UpdateTo:RectangleNode = null; - - /* - public function get Removed() - { - return _Removed; - } - - public function set Removed(r) - { - this._Removed = r; - } - - public function get Host():RectanglePacker - { - return _Host; - } - public function set Host(p:RectanglePacker) - { - this._Host = p; - - if (_Left && _Left.Host != p) - { - throw new Error("bad left host"); - } - if (_Right && _Right.Host != p) - { - throw new Error("bad right host"); - } - if (_Parent && _Parent.Host != p) - { - throw new Error("bad parent host"); - } - - } - - public function get Left():RectangleNode - { - return _Left; - } - public function set Left(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad left host"); - } - _Left = n; - } - public function get Right():RectangleNode - { - return _Right; - } - public function set Right(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad right host"); - } - _Right = n; - } - - public function get Parent():RectangleNode - { - return _Parent; - } - public function set Parent(n:RectangleNode) - { - if (n && n.Host != Host) - { - throw new Error("bad parent host"); - } - _Parent = n; - } - */ - public function get IsFreeSpace() - { - return Left == null && Right == null && !InUse; - } - public function UpdateLinksFromNode(node:RectangleNode) - { - if (node.Parent) - { - if (node.Parent.Left == node) - { - node.Parent.Left = this; - } - if (node.Parent.Right == node) - { - node.Parent.Right = this; - } - } - if (node.Left) - { - node.Left.Parent = this; - } - if (node.Right) - { - node.Right.Parent = this; - } - } - public function MakeFromNode(node:RectangleNode) - { - //_Host = node.Host; - Host = node.Host; - Left = node.Left; - Right = node.Right; - Parent = node.Parent; - AllocationID = node.AllocationID; - InUse = node.InUse; - MinAllocationID = node.MinAllocationID; - NodeID = node.NodeID; - Rect = node.Rect.clone(); - Removed = node.Removed; - DontRemove = node.DontRemove; - } - public function RectangleNode(x, y, w, h, host:RectanglePacker) - { - this.NodeID = NextNodeID++; - this.Host = host; - this.Rect = new Rectangle(x, y, w, h); - } - public function OutputJSON() - { - var node = {}; - node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; - node.in_use = InUse; - node.id = NodeID; - if (this.Left) node.left = this.Left.OutputJSON(); - if (this.Right) node.right = this.Right.OutputJSON(); - return node; - } - - public function ReadJSON(details) - { - details.new_node = this; - this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); - this.Removed = false; - - this.InUse = details.in_use; - - if (details.hasOwnProperty("right")) - { - this.Right = new RectangleNode(0, 0, 0, 0, this.Host); - Right.ReadJSON(details.right); - Right.Parent = this; - } - if (details.hasOwnProperty("left")) - { - this.Left = new RectangleNode(0, 0, 0, 0, this.Host); - Left.ReadJSON(details.left); - Left.Parent = this; - } - } - } -} \ No newline at end of file diff --git a/RectanglePacker.as b/RectanglePacker.as deleted file mode 100755 index b3862ce..0000000 --- a/RectanglePacker.as +++ /dev/null @@ -1,562 +0,0 @@ -package { - import flash.geom.*; - import flash.display.BitmapData; - import flash.display.MovieClip; - import flash.text.TextField; - import flash.events.*; - import flash.sampler.StackFrame; - - public class RectanglePacker - { - protected var w:int; - protected var h:int; - protected var root:RectangleNode; - public var NextAllocationID = 0; - - public function get width():int { return w; } - public function get height():int { return h; } - - public function RectanglePacker(w, h) - { - this.w = w; - this.h = h; - root = new RectangleNode(0, 0, w, h, this); - root.AllocationID = -1; - } - protected var area = 0; - - protected var testRender:MovieClip = new MovieClip(); - - public function GetRoot():RectangleNode - { - return root; - } - - public function GetLeafNodes():Array - { - return GetLeafNodesInternal(root); - } - - protected function GetLeafNodesInternal(n:RectangleNode):Array - { - if (n.InUse) return [n]; - var ret:Array = new Array(); - if (n.Left) ret = GetLeafNodesInternal(n.Left); - if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); - return ret; - } - - public function GetUsedArea() - { - return area; - } - - public function get efficiency() - { - return area / (w * h); - } - - protected function RectCost(w, h) - { - if (w == 0 || h == 0) return 99999999; - return (Math.max(w, h) / Math.min(w, h)) * w * h; - } - - protected function EnumerateTree(r:RectangleNode = null, indent = "") - { - if (r == null) r = this.root; - var str = ""; - str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; - if (r.Left) str += EnumerateTree(r.Left, indent + " "); - if (r.Right) str += EnumerateTree(r.Left, indent + " "); - return str; - } - - /* - * Remove a list of nodes from the tree. - * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree - * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, - leaving the original objects intact (in case something still references them) - */ - public function RemoveNodes(nodes:Array, fullyDestroy = true) - { - - /* DEBUG CHECKS */ - /* - this.PerformDebugCheck(); - - var str = ""; - for (var i = 0; i < nodes.length; i++) - { - str += nodes[i].NodeID + "\n"; - } - - var orig = nodes.concat(); - - var strs = [str, EnumerateTree()]; - - RenderDetailsBox.StartTrack("PackRemoveTime"); - - for (var i = 0; i < nodes.length; i++) - { - var n:RectangleNode = nodes[i]; - if (n.Host != this) - { - throw new Error("bad host!"); - } - } - */ - /* END DEBUG CHECKS */ - - var i, n:RectangleNode, p:RectangleNode; - - // setup the Removed flag on every node that should be removed - // we also check at this time to see if any more nodes need to be removed, such as a parent of - // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - if (n.Host == this) - { - n.Removed = true; - - if (n.InUse) - { - // sum up the total removed area - area -= n.Rect.width * n.Rect.height; - } - - if (n.Parent != null) - { - p = n.Parent; - // check and see if the current node's parent still has any valid children - if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) - { - // all of the current nodes siblings are either being removed or are blank, so - // we can remove the parent too - if (p.Left.IsFreeSpace) - { - // the left child was empty space before, so we can remove it (if it wasn't - // empty space it is already being removed so it doesn't need to be added - // to the list) - if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); - } - if (p.Right.IsFreeSpace) - { - // the right child was empty space before, so we can remove it - if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); - } - if (p != root && nodes.indexOf(p) == -1) - { - // remove the parent node too (provided it isn't the root!) - nodes.push(p); - } - } - } - } - } - - // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, - // so go ahead and remove them - for (i = 0; i < nodes.length; i++) - { - n = nodes[i]; - - if (n.Parent != null) - { - // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not - // also getting removed!) - p = n.Parent; - - if (!p.Removed) - { - if (p.Left && p.Right) - { - var newNode:RectangleNode; - if (p.Left.Removed && p.Right.Removed) - { - // both children were removed, but the parent wasn't, so the parent must be root - // (since we never remove the root) - if (p != root) - { - throw new Error("should be root"); - } - p.Left.Parent = null; - p.Right.Parent = null; - p.Left = null; - p.Right = null; - p.InUse = false; - } else if (!p.Left.Removed) { - // Right node removed, Left node not removed - if (!p.Left.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Right); - newNode.UpdateLinksFromNode(p.Right); - } - // Left node is used - p.Right.InUse = false; - p.Right.Left = null; - p.Right.Right = null; - p.Right.Removed = false; - } else { - throw new Error("should have been caught above!"); - } - } else { - // Left node removed, Right node not removed - if (!p.Right.IsFreeSpace) - { - if (fullyDestroy) - { - // duplicate the node representing empty space so the original node - // remains untouched - newNode = new RectangleNode(0, 0, 0, 0, this); - newNode.MakeFromNode(p.Left); - newNode.UpdateLinksFromNode(p.Left); - } - // Left node is used - //p.Left.Removed = true; - p.Left.InUse = false; - p.Left.Left = null; - p.Left.Right = null; - p.Left.Removed = false; - //p.Left.Parent = null; - } else { - throw new Error("should have been caught above!"); - } - } - } else { - // huh? how does n.Parent == p but p has no children? something went wrong - throw new Error("shouldn't have gotten here"); - } - } - } - //strs.push(EnumerateTree()); - } - } - - public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode - { - - var node:RectangleNode = FindSizedNode(w, h, root); - - if (node == null) - { - //UHOH, texture full - return null; - } - area += w * h; - node.InUse = true; - - var splitVertFirstCost = 0; - if (w < node.Rect.width) - { - splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); - } - - var splitHorizFirstCost = 0; - if (h < node.Rect.height) - { - splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); - } - - - - if (splitVertFirstCost <= splitHorizFirstCost) - { - node.Flags.push("SplitVertFirst"); - if (w < node.Rect.width) - { - node.Flags.push("SplitVert"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - if (h < node.Rect.height) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - } else { - node.Flags.push("SplitHorzFirst"); - if (h < node.Rect.height) - { - node.Flags.push("SplitVert"); - node.InUse = false; - SplitHoriz(node, h); - node.Left.InUse = true; - node = node.Left; - } - if (w < node.Rect.width) - { - node.Flags.push("SplitHorz"); - node.InUse = false; - // split node vertically - SplitVert(node, w); - node.Left.InUse = true; - node = node.Left; - } - } - NextAllocationID++; - if (useInstead) - { - useInstead.MakeFromNode(node); - useInstead.UpdateLinksFromNode(node); - useInstead.Flags = node.Flags; - node = useInstead; - node.Flags.push("UseInstead"); - } - - //if (!CheckOKNode(node)) node.Flags.push("BadNode"); - - return node; - } - public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) - { - if (r == null) r = this.root; - if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) - { - var ancestor:RectangleNode = FindCommonNode(n, r); - throw new Error("bad node allocated!"); - return false; - } - var ok = true; - if (r.Left) ok = ok && CheckOKNode(n, r.Left); - if (r.Right) ok = ok && CheckOKNode(n, r.Right); - return ok; - } - - public function PerformDebugCheck() - { - DebugInternal(this.root); - } - - protected function DebugInternal(n:RectangleNode) - { - if (n.Host != this) - { - throw new Error("problem with host!"); - } - if (n.IsFreeSpace) - { - if (n.Left || n.Right) - { - throw new Error("shouldn't have children"); - } - } - if ((n.Left && !n.Right) || (n.Right && !n.Left)) - { - throw new Error("mismatched children"); - } - if (n.Left && n.Left.Parent != n) - { - throw new Error("left child has bad parent"); - } - if (n.Right && n.Right.Parent != n) - { - throw new Error("right child has bad parent"); - } - if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) - { - throw new Error("problem with parent"); - } - if (n.Left) DebugInternal(n.Left); - if (n.Right) DebugInternal(n.Right); - } - - public function FindCommonNode(a:RectangleNode, b:RectangleNode) - { - var aHistory = []; - var bHistory = []; - while (a != null) - { - aHistory.push(a); - a = a.Parent; - } - while (b != null) - { - bHistory.push(b); - b = b.Parent; - } - var i = aHistory.length - 1; - var j = bHistory.length - 1; - var same = null; - while (i >= 0 && j >= 0) - { - if (aHistory[i] == bHistory[j]) - { - same = aHistory[i]; - } else { - break; - } - i--; - j--; - } - return same; - } - - public function TestRender() - { - while (testRender.numChildren > 0) - { - testRender.removeChildAt(0); - } - testRender.graphics.clear(); - TestRenderNode(root, testRender); - return testRender; - } - protected function TestRenderNode(n:RectangleNode, m:MovieClip) - { - var g:MovieClip = new MovieClip(); - m.addChild(g); - g.graphics.lineStyle(1, 0, 1); - if (n.Left != null) TestRenderNode(n.Left, m); - if (n.Left != null) TestRenderNode(n.Right, m); - if (n.InUse) - { - g.graphics.beginFill(0xFFFF00, 0.2); - } - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - if (n.InUse) - { - g.graphics.endFill(); - var t:TextField = new TextField(); - t.text = n.NodeID; - t.x = n.Rect.x + n.Rect.width / 2.0; - t.y = n.Rect.y + n.Rect.height / 2.0; - g.addChild(t); - g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); - g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); - } - - } - public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) - { - if (n.InUse) - { - //_trace(Math.round(n.LastAccessTime / 1000)); - } - var p:RectangleNode = n.Parent; - if (p) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); - g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); - g.graphics.endFill(); - t.text = p.NodeID; - if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); - g.oldListener = function(e){MouseOver(p, g, t);}; - g.addEventListener(MouseEvent.CLICK, g.oldListener); - } - } - public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) - { - g.graphics.clear(); - g.graphics.lineStyle(1, 0, 1); - g.graphics.beginFill(0xFFFF00, 0.2); - g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); - g.graphics.endFill(); - t.text = n.NodeID; - } - protected function SplitVert(node:RectangleNode, leftWidth) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function SplitHoriz(node:RectangleNode, topHeight) - { - node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); - node.Left.AllocationID = NextAllocationID; - node.Left.Parent = node; - node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); - node.Right.AllocationID = NextAllocationID; - node.Right.Parent = node; - - //CheckOKNode(node.Left); - //CheckOKNode(node.Right); - } - protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode - { - if (node.InUse) return null; - if (node.Rect.width >= w && node.Rect.height >= h) - { - if (node.Left != null && node.Right != null) - { - var t:RectangleNode = FindSizedNode(w, h, node.Left); - if (t != null) return t; - t = FindSizedNode(w, h, node.Right); - return t; - } else { - return node; - } - } - return null; - } - - public function LoadTree(details) - { - this.root = new RectangleNode(0, 0, 0, 0, this); - root.ReadJSON(details); - - this.NextAllocationID = 0; - this.area = 0; - - var queue:Array = new Array(); - queue.push(root); - while (queue.length > 0) - { - var node:RectangleNode = queue.shift(); - node.AllocationID = NextAllocationID; - node.MinAllocationID = NextAllocationID; - if (node.Left) queue.push(node.Left); - if (node.Right) queue.push(node.Right); - if (node.InUse) this.area += node.Rect.width * node.Rect.height; - } - NextAllocationID++; - } - - public function GetNodePath(node:RectangleNode) - { - var output:String = ""; - while (node != this.root) - { - output = (node == node.Parent.Left ? "l" : "r") + output; - node = node.Parent; - } - return output; - } - - public function GetNodeFromPath(path:String):RectangleNode - { - var node:RectangleNode = this.root; - for (var i = 0; i < path.length; i++) - { - if (!node) return null; - if (path.charAt(i) == "r") - { - node = node.Right; - } else { - node = node.Left; - } - } - return node; - } - } -} \ No newline at end of file diff --git a/Utils.as b/Utils.as deleted file mode 100644 index 45db712..0000000 --- a/Utils.as +++ /dev/null @@ -1,389 +0,0 @@ -package -{ - import flash.display.*; - import flash.geom.*; - public class Utils - { - public static function GetChildren(clip:MovieClip):Array - { - var ret:Array = []; - for (var i = 0; i < clip.numChildren; i++) - { - ret.push(clip.getChildAt(i)); - } - return ret; - } - - /* - * angle difference - * (range -Math.PI to Math.PI) - */ - public static function GetAngleDiff(a, b) - { - var angleDiff = b - a; - - while (angleDiff > Math.PI) - { - angleDiff -= Math.PI * 2; - } - while (angleDiff < -Math.PI) - { - angleDiff += Math.PI * 2; - } - return angleDiff; - } - - /* - * angle difference - * (range 0 to Math.PI) - */ - public static function GetAngleDiffAbs(a, b) - { - var angleDiff = GetAngleDiff(a, b); - while (angleDiff < 0) - { - angleDiff += Math.PI * 2; - } - - if (angleDiff > Math.PI) - { - angleDiff = Math.PI * 2 - angleDiff; - } - - return angleDiff; - } - - public static function GetTransform(from:Matrix, to:Matrix) - { - var i:Matrix = from.clone(); - i.invert(); - var m:Matrix = to.clone(); - m.concat(i); - return m; - } - - public static function Decompose(m:Matrix) - { - var s:Point = ScaleFromMat(m); - m = m.clone(); - - var sxUnit = s.x >= 0 ? 1 : -1; - var syUnit = s.y >= 0 ? 1 : -1; - - m.scale(sxUnit, syUnit); - - //m.a /= sxUnit; - //m.d /= syUnit; - var rot = RotFromMat(m); - return {sx:s.x, sy:s.y, rot:rot}; - } - - public static function RotFromMat(m:Matrix) - { - return Math.atan2(-m.c, m.a); - } - - public static function ScaleFromMat(m:Matrix):Point - { - var xAxisX = m.a; - var xAxisY = m.c; - - var yAxisX = m.b; - var yAxisY = m.d; - - var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); - if (m.a < 0) sx *= -1; - - var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); - if (m.d < 0) sy *= -1; - - return new Point(sx, sy); - } - - public static function TransformRect(r:Rectangle, m:Matrix) - { - var p1:Point = new Point(r.left, r.top); - var p2:Point = new Point(r.right, r.top); - var p3:Point = new Point(r.left, r.bottom); - var p4:Point = new Point(r.right, r.bottom); - - p1 = m.transformPoint(p1); - p2 = m.transformPoint(p2); - p3 = m.transformPoint(p3); - p4 = m.transformPoint(p4); - - r.left = Math.min(p1.x, p2.x, p3.x, p4.x); - r.top = Math.min(p1.y, p2.y, p3.y, p4.y); - r.right = Math.max(p1.x, p2.x, p3.x, p4.x); - r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); - } - - public static function RoundRect(r:Rectangle) - { - r.left = Math.floor(r.left); - r.top = Math.floor(r.top); - r.right = Math.ceil(r.right); - r.bottom = Math.ceil(r.bottom); - } - - public static function ScaleRect(r:Rectangle, s) - { - r.left *= s; - r.top *= s; - r.right *= s; - r.bottom *= s; - } - - public static function RecursivelyStop(clip) - { - if (clip is MovieClip) - { - clip.stop(); - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function WeirdGotoFrame(clip:MovieClip, frame) - { - var dir = clip.currentFrame > frame ? -1 : 1; - while (clip.currentFrame != frame) - { - RecurseDir(clip, dir); - } - } - - protected static function RecurseDir(clip:MovieClip, dir) - { - for (var i = 0; i < clip.numChildren; i++) - { - var child = clip.getChildAt(i); - if (child is MovieClip) - { - RecurseDir(child, dir); - } - } - if (dir == 1) - { - clip.nextFrame(); - } else { - clip.prevFrame(); - } - } - - protected static var tempSpace:BitmapData = null; - protected static var tempSpaceRect:Rectangle = new Rectangle(); - protected static var tempSpaceMatrix:Matrix = new Matrix(); - protected static var tempSpaceZero:Point = new Point(); - protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); - protected static var lastDrawOffset:Point = new Point(); - public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle - { - if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); - - var oldPad = 0; - var padAmount = 5; - - var ret:Rectangle = new Rectangle(); - - var baseBounds:Rectangle = clip.getBounds(clip); - - var boundsClip:DisplayObject = null; - if (clip is DisplayObjectContainer) - { - boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); - } - - if (boundsClip != null) - { - baseBounds = boundsClip.getBounds(clip); - } - - if (useMatrix) - { - TransformAABBRect(baseBounds, useMatrix); - } - - if (boundsClip != null) - { - return baseBounds; - } - - var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); - var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); - if (tempSpace == null) - { - tempSpace = new BitmapData(minW, minH, true, 0x0); - } - if (tempSpace.width < minW || tempSpace.height < minH) - { - tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); - } - - var r:Rectangle = new Rectangle(); - - baseBounds.left = Math.floor(baseBounds.left); - baseBounds.right = Math.ceil(baseBounds.right); - - baseBounds.top = Math.floor(baseBounds.top); - baseBounds.bottom = Math.ceil(baseBounds.bottom); - - var i; - - var needsChecking = true; - while (needsChecking) - { - needsChecking = false; - r.left = baseBounds.left - padAmount; - r.right = baseBounds.right + padAmount; - - r.top = baseBounds.top - padAmount; - r.bottom = baseBounds.bottom + padAmount; - - ret = r.clone(); - - tempSpaceRect.x = tempSpaceRect.y = 0; - tempSpaceRect.width = tempSpace.width; - tempSpaceRect.height = tempSpace.height; - tempSpace.fillRect(tempSpaceRect, 0x0); - - tempSpaceMatrix.identity(); - if (useMatrix) - { - tempSpaceMatrix.a = useMatrix.a; - tempSpaceMatrix.b = useMatrix.b; - tempSpaceMatrix.c = useMatrix.c; - tempSpaceMatrix.d = useMatrix.d; - tempSpaceMatrix.tx = useMatrix.tx; - tempSpaceMatrix.ty = useMatrix.ty; - } - tempSpaceMatrix.translate(-r.left, -r.top); - - lastDrawOffset.x = -r.left; - lastDrawOffset.y = -r.top; - tempSpace.draw(clip, tempSpaceMatrix); - - tempSpaceRect.width = 1; - tempSpaceRect.height = r.height; - - var sideMovedIn = 0; - for (i = 0; i < r.width; i++) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.left++; - sideMovedIn++; - } - } - if (ret.left < baseBounds.left - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.width - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.x = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.right--; - } - } - if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - sideMovedIn = 0; - tempSpaceRect.width = r.width; - tempSpaceRect.height = 1; - tempSpaceRect.x = 0; - for (i = 0; i < r.height; i++) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.top++; - sideMovedIn++; - } - } - if (ret.top < baseBounds.top - oldPad - 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - - for (i = r.height - 1; i >= sideMovedIn; i--) - { - tempSpaceRect.y = i; - if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) - { - break; - } else { - ret.bottom--; - } - } - if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) - { - oldPad = padAmount; - padAmount += 20; - needsChecking = true; - continue; - } - } - return ret; - } - - public static function TransformAABBRect(r:Rectangle, m:Matrix) - { - var o1X = r.left; - var o1Y = r.top; - - var o2X = r.right; - var o2Y = r.top; - - var o3X = r.left; - var o3Y = r.bottom; - - var o4X = r.right; - var o4Y = r.bottom; - - var n1X = o1X * m.a + o1Y * m.c + m.tx; - var n1Y = o1X * m.b + o1Y * m.d + m.ty; - - var n2X = o2X * m.a + o2Y * m.c + m.tx; - var n2Y = o2X * m.b + o2Y * m.d + m.ty; - - var n3X = o3X * m.a + o3Y * m.c + m.tx; - var n3Y = o3X * m.b + o3Y * m.d + m.ty; - - var n4X = o4X * m.a + o4Y * m.c + m.tx; - var n4Y = o4X * m.b + o4Y * m.d + m.ty; - - r.left = Math.min(n1X, n2X, n3X, n4X); - r.right = Math.max(n1X, n2X, n3X, n4X); - - r.top = Math.min(n1Y, n2Y, n3Y, n4Y); - r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); - } - } -} \ No newline at end of file diff --git a/blooddy_crypto/LICENSE.md b/blooddy_crypto/LICENSE.md deleted file mode 100755 index 00ad983..0000000 --- a/blooddy_crypto/LICENSE.md +++ /dev/null @@ -1,24 +0,0 @@ -MIT License -=========== - -Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by - ------------ -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - ------------ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/blooddy_crypto/blooddy_crypto.swc b/blooddy_crypto/blooddy_crypto.swc deleted file mode 100755 index ba33cc4..0000000 --- a/blooddy_crypto/blooddy_crypto.swc +++ /dev/null Binary files differ diff --git a/com/adobe/images/PNGEncoderWithAlpha.as b/com/adobe/images/PNGEncoderWithAlpha.as deleted file mode 100644 index 32b1b20..0000000 --- a/com/adobe/images/PNGEncoderWithAlpha.as +++ /dev/null @@ -1,151 +0,0 @@ -/* - Adobe Systems Incorporated(r) Source Code License Agreement - Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. - - Please read this Source Code License Agreement carefully before using - the source code. - - Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, - no-charge, royalty-free, irrevocable copyright license, to reproduce, - prepare derivative works of, publicly display, publicly perform, and - distribute this source code and such derivative works in source or - object code form without any attribution requirements. - - The name "Adobe Systems Incorporated" must not be used to endorse or promote products - derived from the source code without prior written permission. - - You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and - against any loss, damage, claims or lawsuits, including attorney's - fees that arise or result from your use or distribution of the source - code. - - THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT - ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, - BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF - NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA - OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -package com.adobe.images -{ - import flash.geom.*; - import flash.display.Bitmap; - import flash.display.BitmapData; - import flash.utils.ByteArray; - - /** - * Class that converts BitmapData into a valid PNG - */ - public class PNGEncoderWithAlpha - { - /** - * Created a PNG image from the specified BitmapData - * - * @param image The BitmapData that will be converted into the PNG format. - * @return a ByteArray representing the PNG encoded image data. - * @langversion ActionScript 3.0 - * @playerversion Flash 9.0 - * @tiptext - */ - public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { - var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - for(var i:int=0;i < img.height;i++) { - // no filter - IDAT.writeByte(0); - var p:uint; - var j:int; - var a:uint; - if ( !hasAlpha) { - for(j=0;j < img.width;j++) { - p = img.getPixel(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)|0xFF)); - } - } else { - for(j=0;j < img.width;j++) { - p = img.getPixel32(j,i); - a = p >>> 24; - if (alphaChannel != null && alphaChannel.transparent) - { - a = alphaChannel.getPixel32(j, i) >>> 24; - } - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - a)); - } - } - } - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - return png; - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - var c:uint; - for (var n:uint = 0; n < 256; n++) { - c = n; - for (var k:uint = 0; k < 8; k++) { - if (c & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - c = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - uint(0xff)] ^ uint(c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/driver.py b/driver.py index bba07d6..a63c26e 100644 --- a/driver.py +++ b/driver.py @@ -17,6 +17,9 @@ self.stdin = None self.conn = None + def make_exporter_path(self, prog_name): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), prog_name) + def start(self): self.sock = socket.socket() self.sock.bind(("localhost", self.port)) @@ -25,9 +28,9 @@ self.sock.listen(0) if not self.exporter_already_running: - exporter_proc_args = [os.getcwd() + "/Exporter.exe"] + exporter_proc_args = [self.make_exporter_path("flash/Exporter.exe")] if self.use_air: - exporter_proc_args = [os.getcwd() + "/Exporter.app/Expoter.exe", str(self.port)] + exporter_proc_args = [self.make_exporter_path("Exporter.app/Expoter.exe"), str(self.port)] self.proc = subprocess.Popen(exporter_proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) diff --git a/flash/DebugExporter-app.xml b/flash/DebugExporter-app.xml new file mode 100644 index 0000000..e2ff06e --- /dev/null +++ b/flash/DebugExporter-app.xml @@ -0,0 +1,38 @@ + + + + DebugExporter + 1.0 + DebugExporter + + DebugExporter + + + DebugExporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/DebugExporter.fla b/flash/DebugExporter.fla new file mode 100644 index 0000000..9f0dff6 --- /dev/null +++ b/flash/DebugExporter.fla Binary files differ diff --git a/flash/DebugExporter.swf b/flash/DebugExporter.swf new file mode 100644 index 0000000..d08d5d4 --- /dev/null +++ b/flash/DebugExporter.swf Binary files differ diff --git a/flash/Exporter-app.xml b/flash/Exporter-app.xml new file mode 100644 index 0000000..7deb7c5 --- /dev/null +++ b/flash/Exporter-app.xml @@ -0,0 +1,38 @@ + + + + Exporter + 1.0 + Exporter + + Exporter + + + Exporter.swf + standard + false + true + false + portrait + auto + + + false + false + diff --git a/flash/Exporter.as b/flash/Exporter.as new file mode 100644 index 0000000..8e17b87 --- /dev/null +++ b/flash/Exporter.as @@ -0,0 +1,309 @@ +package +{ + import flash.display.*; + import flash.net.*; + import flash.events.*; + import flash.desktop.*; + import flash.errors.*; + import flash.system.*; + import flash.utils.*; + import by.blooddy.crypto.*; + import job.*; + + public class Exporter extends MovieClip + { + public static var Instance:Exporter = null; + + public static var DefaultPort:int = 7890; + private var driver:Socket = null; + private var debug:Boolean = false; + public function Exporter() + { + Instance = this; + + try + { + NativeApplication.nativeApplication.addEventListener("invoke", ApplicationInvoked); + } + catch (e) + { + // not an air runtime app + ConnectDriver(DefaultPort); // try default port + } + } + + public function ApplicationInvoked(e) + { + if (e.arguments.length == 1) + { + ConnectDriver(parseInt(e.arguments[0])); + } + else + { + ConnectDriver(DefaultPort); + } + } + + private var connected:Boolean = false; + private var lastPort:int; + private function ConnectDriver(port:int, firstTime:Boolean = true) + { + this.lastPort = port; + if (firstTime) + { + Trace("Attempting to connect to driver"); + } + try + { + var s:Socket = new Socket(); + s.addEventListener(IOErrorEvent.IO_ERROR, DriverError); + s.addEventListener(Event.CONNECT, DriverConnected); + s.addEventListener(Event.CLOSE, DriverClosed); + s.connect("localhost", port); + } + catch (e) + { + Trace("Error establishing wrapper connection"); + } + } + + private function DriverClosed(e) + { + connected = false; + if (debug) + { + ConnectDriver(lastPort); + } + else + { + Quit(); + } + } + + private function DriverError(e) + { + if (!debug) + { + Trace(" Failed to connect"); + } + if (debug && !connected) + { + setTimeout(ConnectDriver, 500, lastPort, false); + } + } + + private function DriverConnected(e) + { + connected = true; + Trace(" Connected"); + driver = e.target as Socket; + driver.addEventListener(ProgressEvent.SOCKET_DATA, DriverRecv); + } + + private function Quit() + { + fscommand("quit"); + try + { + NativeApplication.nativeApplication.exit(); + } catch (e) + { + + } + } + + private var jobQueue:Array = new Array(); + private var activeJob:Job = null; + private function QueueJob(jobParams) + { + if (!jobParams.hasOwnProperty("id")) + { + Print("Failure: job details didn't contain job id"); + CheckNewJob(); + return; + } + var id:int = parseInt(jobParams.id); + + if (!jobParams.hasOwnProperty("graphics") || getQualifiedClassName(jobParams.graphics) != "Array") + { + Print("Failure: job " + id + " details didn't contain graphics array"); + JobFailed(id); + return; + } + var graphicsDetails:Array = jobParams.graphics; + + delete jobParams.command; + delete jobParams.id; + delete jobParams.graphics; + + var j:Job = new Job(id, graphicsDetails); + jobQueue.push(j); + CheckNewJob(); + } + + private function JobFailed(id:int) + { + DriverCommand("done", {id:id}); + CheckNewJob(); + } + + private function CheckNewJob() + { + if (activeJob == null && jobQueue.length > 0) + { + activeJob = jobQueue.shift(); + activeJob.Go(JobComplete); + } + } + + private function JobComplete() + { + Trace("Done: " + activeJob.GetID()); + + var data = activeJob.GetData(); + var resources:Array = activeJob.GetResources().map(function(r:ByteArray, i, arr) { return Base64.encode(r); }); + DriverCommand("done", {id:activeJob.GetID(), data:data, resources:resources}); + + activeJob = null; + CheckNewJob(); + } + + private function DispatchCommand(cmdData) + { + try + { + if (cmdData.hasOwnProperty("command")) + { + var cmd = "" + cmdData.command; + //Trace("cmd: " + cmd); + switch (cmd) + { + case "trace": + Trace(cmdData.string); + break; + case "exit": + Quit(); + break; + case "job": + QueueJob(cmdData); + break; + default: + Trace("Recv unknown: " + JSON.stringify(cmdData)); + break; + } + } + } catch (e) + { + Print(e.getStackTrace()); + } + } + + private var buffer:ByteArray = new ByteArray(); + private var swpBuffer:ByteArray = new ByteArray(); + private function DriverRecv(e) + { + var oldPos = buffer.position; + //Trace("recv"); + try + { + driver.readBytes(buffer, buffer.length, driver.bytesAvailable); + //Trace(buffer.length - buffer.position); + var len:uint = buffer.readUnsignedInt(); + var msg = buffer.readUTFBytes(len); + + buffer.readBytes(swpBuffer); + buffer.clear(); + + var tmp = buffer; + buffer = swpBuffer; + swpBuffer = tmp; + + var cmdData = JSON.parse(msg); + DispatchCommand(cmdData); + } + catch (eof:EOFError) + { + buffer.position = oldPos; + //Trace("Waiting for more data... " + driver.bytesAvailable + " " + (buffer.length - buffer.position)); + // wait for more data + } + catch (err:IOError) + { + Trace("Driver IO error"); + } + catch (err) + { + Trace("Problem reading from driver:\n" + err.toString()); + } + } + + private function DriverCommand(cmd:String, data = null) + { + var obj = {command:cmd}; + if (data != null) + { + for (var k in data) + { + obj[k] = data[k]; + } + } + var str:String = JSON.stringify(obj); + DriverSend(str); + } + + private function DriverSend(str:String) + { + if (driver != null) + { + driver.writeUnsignedInt(uint(str.length)); + driver.writeUTFBytes(str); + driver.flush(); + } + } + + public function Trace(str) + { + str = "" + str; + traceText.x = 2; + + trace(str); + traceText.width = stage.stageWidth - 4; + traceText.height = stage.stageHeight + 100; + if (traceText.text == "") + { + traceText.text = str; + } + else + { + traceText.appendText("\n" + str); + } + while (traceText.textHeight > traceText.height) + { + var split = traceText.text.indexOf("\n"); + if (split == -1) + { + traceText.height = traceText.textHeight + 5; + break; + } + traceText.text = traceText.text.substr(split + 1); + } + traceText.y = stage.stageHeight - traceText.textHeight - 2; + } + + public function Print(str:String, localTrace:Boolean = true) + { + if (localTrace || driver == null) + { + Trace(str); + } + else + { + trace(str); + } + if (driver != null) + { + DriverCommand("print", {string:str + "\n"}); + } + } + } +} \ No newline at end of file diff --git a/flash/Exporter.exe b/flash/Exporter.exe new file mode 100644 index 0000000..c305dbf --- /dev/null +++ b/flash/Exporter.exe Binary files differ diff --git a/flash/Exporter.fla b/flash/Exporter.fla new file mode 100644 index 0000000..83dfa3e --- /dev/null +++ b/flash/Exporter.fla Binary files differ diff --git a/flash/Exporter.swf b/flash/Exporter.swf new file mode 100644 index 0000000..977883f --- /dev/null +++ b/flash/Exporter.swf Binary files differ diff --git a/flash/blooddy_crypto/LICENSE.md b/flash/blooddy_crypto/LICENSE.md new file mode 100644 index 0000000..00ad983 --- /dev/null +++ b/flash/blooddy_crypto/LICENSE.md @@ -0,0 +1,24 @@ +MIT License +=========== + +Copyright (C) 2010 Nick Ryzhy / blooddy@tut.by / www.blooddy.by + +----------- +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +----------- +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/flash/blooddy_crypto/blooddy_crypto.swc b/flash/blooddy_crypto/blooddy_crypto.swc new file mode 100644 index 0000000..ba33cc4 --- /dev/null +++ b/flash/blooddy_crypto/blooddy_crypto.swc Binary files differ diff --git a/flash/com/adobe/images/PNGEncoderWithAlpha.as b/flash/com/adobe/images/PNGEncoderWithAlpha.as new file mode 100644 index 0000000..32b1b20 --- /dev/null +++ b/flash/com/adobe/images/PNGEncoderWithAlpha.as @@ -0,0 +1,151 @@ +/* + Adobe Systems Incorporated(r) Source Code License Agreement + Copyright(c) 2005 Adobe Systems Incorporated. All rights reserved. + + Please read this Source Code License Agreement carefully before using + the source code. + + Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable copyright license, to reproduce, + prepare derivative works of, publicly display, publicly perform, and + distribute this source code and such derivative works in source or + object code form without any attribution requirements. + + The name "Adobe Systems Incorporated" must not be used to endorse or promote products + derived from the source code without prior written permission. + + You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and + against any loss, damage, claims or lawsuits, including attorney's + fees that arise or result from your use or distribution of the source + code. + + THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT + ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, + BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ALSO, THERE IS NO WARRANTY OF + NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT. IN NO EVENT SHALL MACROMEDIA + OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +package com.adobe.images +{ + import flash.geom.*; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.utils.ByteArray; + + /** + * Class that converts BitmapData into a valid PNG + */ + public class PNGEncoderWithAlpha + { + /** + * Created a PNG image from the specified BitmapData + * + * @param image The BitmapData that will be converted into the PNG format. + * @return a ByteArray representing the PNG encoded image data. + * @langversion ActionScript 3.0 + * @playerversion Flash 9.0 + * @tiptext + */ + public static function encode(img:BitmapData, alphaChannel:BitmapData = null):ByteArray { + var hasAlpha = img.transparent || (alphaChannel != null && alphaChannel.transparent); + // Create output byte array + var png:ByteArray = new ByteArray(); + // Write PNG signature + png.writeUnsignedInt(0x89504e47); + png.writeUnsignedInt(0x0D0A1A0A); + // Build IHDR chunk + var IHDR:ByteArray = new ByteArray(); + IHDR.writeInt(img.width); + IHDR.writeInt(img.height); + IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA + IHDR.writeByte(0); + writeChunk(png,0x49484452,IHDR); + // Build IDAT chunk + var IDAT:ByteArray= new ByteArray(); + for(var i:int=0;i < img.height;i++) { + // no filter + IDAT.writeByte(0); + var p:uint; + var j:int; + var a:uint; + if ( !hasAlpha) { + for(j=0;j < img.width;j++) { + p = img.getPixel(j,i); + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)|0xFF)); + } + } else { + for(j=0;j < img.width;j++) { + p = img.getPixel32(j,i); + a = p >>> 24; + if (alphaChannel != null && alphaChannel.transparent) + { + a = alphaChannel.getPixel32(j, i) >>> 24; + } + IDAT.writeUnsignedInt( + uint(((p&0xFFFFFF) << 8)| + a)); + } + } + } + IDAT.compress(); + writeChunk(png,0x49444154,IDAT); + // Build IEND chunk + writeChunk(png,0x49454E44,null); + // return PNG + return png; + } + + private static var crcTable:Array; + private static var crcTableComputed:Boolean = false; + + private static function writeChunk(png:ByteArray, + type:uint, data:ByteArray):void { + if (!crcTableComputed) { + crcTableComputed = true; + crcTable = []; + var c:uint; + for (var n:uint = 0; n < 256; n++) { + c = n; + for (var k:uint = 0; k < 8; k++) { + if (c & 1) { + c = uint(uint(0xedb88320) ^ + uint(c >>> 1)); + } else { + c = uint(c >>> 1); + } + } + crcTable[n] = c; + } + } + var len:uint = 0; + if (data != null) { + len = data.length; + } + png.writeUnsignedInt(len); + var p:uint = png.position; + png.writeUnsignedInt(type); + if ( data != null ) { + png.writeBytes(data); + } + var e:uint = png.position; + png.position = p; + c = 0xffffffff; + for (var i:int = 0; i < (e-p); i++) { + c = uint(crcTable[ + (c ^ png.readUnsignedByte()) & + uint(0xff)] ^ uint(c >>> 8)); + } + c = uint(c^uint(0xffffffff)); + png.position = e; + png.writeUnsignedInt(c); + } + } +} \ No newline at end of file diff --git a/flash/frame/FrameInfo.as b/flash/frame/FrameInfo.as new file mode 100644 index 0000000..c855f3b --- /dev/null +++ b/flash/frame/FrameInfo.as @@ -0,0 +1,20 @@ +package frame +{ + import flash.display.*; + import flash.geom.*; + public class FrameInfo + { + public var frameData:BitmapData; + public var drawMatrix:Matrix; + public var sourceRect:Rectangle; + + public var rect:Rectangle; + public var sheetIndex:int; + public function FrameInfo(b:BitmapData, drawMatrix:Matrix, sourceRect:Rectangle) + { + frameData = b; + this.drawMatrix = drawMatrix; + this.sourceRect = sourceRect; + } + } +} diff --git a/flash/frame/FramePacker.as b/flash/frame/FramePacker.as new file mode 100644 index 0000000..0f32cd2 --- /dev/null +++ b/flash/frame/FramePacker.as @@ -0,0 +1,126 @@ +package frame +{ + import flash.geom.*; + import flash.display.*; + import util.*; + public class FramePacker + { + public const MaxSize:int = 2048; + private var sheets:Array; // [RectanglePacker] + private var frames:Array; // [FrameInfo] + + public function GetSheets():Array + { + return sheets; + } + + public function FramePacker(frames:Array) + { + this.frames = frames.filter(function(i:FrameInfo, index, arr) { return i.frameData != null; }, this); + this.frames.sortOn("frameData", Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + } + + private function GetMaxSize(frames:Array):Point + { + if (frames.length == 0) return new Point(); + return new Point(Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.width; }, this)), + Math.max.apply(Math, frames.map(function(i:FrameInfo, index, arr) { return i.frameData.height; }, this))); + } + + private function GetArea(frames:Array):int + { + var area = 0; + for (var i in frames) + { + if (frames[i] is FrameInfo) + { + area += frames[i].frameData.width * frames[i].frameData.height; + } + if (frames[i] is BitmapData || frames[i] is Rectangle) + { + area += frames[i].width * frames[i].height; + } + } + return area; + } + + public const AreaUsedMultiplier = 1.3; // guess how much more sheet space we use than actual space taken up by frames + + private var callback; + public function Pack(callback) + { + this.callback = callback; + sheets = new Array(); + var index = 0; + while (index < frames.length) + { + var now:Array = frames.slice(index); + + var max:Point = GetMaxSize(now); + var area:int = GetArea(now); + + var exponent = Math.floor(Math.log(Math.sqrt(area * AreaUsedMultiplier)) / Math.log(2)); + var sizeX:int = Math.min(MaxSize, Math.pow(2, exponent)); + var sizeY:int = sizeX; + + var i; + + var startIndex = index; + var nodes:Array = new Array(); + while (startIndex == index) + { + nodes.length = 0; + var sheet:RectanglePacker = new RectanglePacker(sizeX, sizeY); + //var sorted:Array = now.sortOn("frameData", Array.RETURNINDEXEDARRAY | Array.DESCENDING, function(a:BitmapData, b:BitmapData) { return (a.width * a.height) - (b.width - b.height); }); + + //for (var sortedI = 0; sortedI < now.length; sortedI++) + for (i = 0; i < now.length; i++) + { + //i = sorted[sortedI]; + var node:RectangleNode = sheet.Insert(now[i].frameData.width, now[i].frameData.height); + if (node == null) + { + break; + } + nodes.push(node); + } + if (nodes.length == now.length) + { + // stop the loop, attempt the 75% check here + index += nodes.length; + } + else + { + if (sizeX == sizeY) + { + sizeX *= 2; + } + else + { + sizeY *= 2; + } + if (sizeX > MaxSize || sizeY > MaxSize) + { + if (nodes.length == 0) + { + Exporter.Instance.Print("Failure: item too large to pack on sheet"); + callback(false); + return; + } + index += nodes.length; + } + } + } + + for (i = startIndex; i < index; i++) + { + frames[i].sheetIndex = sheets.length; + frames[i].rect = nodes[i - startIndex].Rect; + } + sheets.push(sheet); + } + + callback(true); + } + } +} diff --git a/flash/frame/IFramesSource.as b/flash/frame/IFramesSource.as new file mode 100644 index 0000000..dd3bb10 --- /dev/null +++ b/flash/frame/IFramesSource.as @@ -0,0 +1,9 @@ +package frame +{ + public interface IFramesSource + { + function Go(callback); + function GetFrames():Array; + function GetData(); + } +} diff --git a/flash/generator/AnimatedSkeletonGenerator.as b/flash/generator/AnimatedSkeletonGenerator.as new file mode 100644 index 0000000..528687a --- /dev/null +++ b/flash/generator/AnimatedSkeletonGenerator.as @@ -0,0 +1,655 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import skeletal.*; + import util.*; + + public class AnimatedSkeletonGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + public function get Def():GraphicExportDef { return def; } + private var callback; + private var sequences:Array; + private var frames:Array; + public function GetFrames():Array + { + return frames; + } + public function GetData() + { + var usedPieces:Array = library.GetAllUsedPieces(); + var pieces:Array = usedPieces.map(function(p:Piece, i, arr) + { + var r = {x:p.Frame.rect.x, y:p.Frame.rect.y, w:p.Frame.rect.width, h:p.Frame.rect.height}; + var c = {x:p.CenterPoint.x, y:p.CenterPoint.y}; + return {rect:r, center:c, resource:p.Frame.sheetIndex}; + }); + return { + pieces:pieces, + scale:def.scale, + sequences:sequences.map( + function(s:Sequence, i, arr) + { + return { + length:s.Length, + pieces:s.PieceSequences.map( + function (ps:PieceSequence, i, arr) + { + var frames:Array = new Array(); + for (var i = 0; i < s.Length; i++) + { + var pfi:PieceFrameInfo = ps.GetFrame(i + 1); + var frameObj = + { + present:pfi.Present, + depth:pfi.Depth + }; + if (pfi.Present) + { + frameObj.transform = [pfi.Transform.a, pfi.Transform.b, pfi.Transform.c, pfi.Transform.d, pfi.Transform.tx, pfi.Transform.ty]; + } + frames.push(frameObj); + } + return {piece_index:usedPieces.indexOf(ps.GetPiece()), frames:frames}; + } + ) + }; + } + ) + }; + } + public function AnimatedSkeletonGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + private var library:PieceLibrary + public function Go(callback) + { + sequences = new Array(); + library = new PieceLibrary(); + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + var s:Sequence = new Sequence(this, library, i, c); + s.GetAnimation(); + sequences.push(s); + break; + } + } + } + + frames = library.GetAllUsedPieces().map( + function(p:Piece, i, arr) + { + return p.Frame; + } + ); + + callback(true); + } + + public static function IsFullPiece(baseClip:DisplayObject, parentClip:MovieClip, clip:DisplayObject) + { + //if (HasAnyNamedChildren(clip)) return false; + + //if (!clip.name.match("^instance\\d+$")) return true; + + if (parentClip.totalFrames != 1) return false; + + //if (clip == baseClip || (clip.parent && clip.parent == baseClip)) return false; + if (clip is MovieClip) + { + var m:MovieClip = clip as MovieClip; + if (m.totalFrames > 1) return false; + + if (!m.name.match("^instance\\d+$")) return false; + + for (var i = 0; i < m.numChildren; i++) + { + var c = m.getChildAt(i); + if (!IsFullPiece(baseClip, m, c)) return false; + } + } + return true; + } + } +} + +class Sequence +{ + import flash.display.*; + import flash.geom.*; + import generator.AnimatedSkeletonGenerator; + import skeletal.*; + import frame.FrameInfo; + import util.*; + import job.GraphicExportDef; + + private var pieces:Array = new Array(); + private var pieceSequences:Array = new Array(); + public function get PieceSequences():Array { return pieceSequences; } + private var src:MovieClip; + private var seq:int; + private var seqLength:int; + public function get Length():int { return seqLength; } + private var library:PieceLibrary; + private var gen:AnimatedSkeletonGenerator; + + public function Sequence(gen:AnimatedSkeletonGenerator, library:PieceLibrary, seq:int, src:MovieClip) + { + this.gen = gen; + this.library = library; + this.seq = seq; + this.seqLength = src.totalFrames; + this.src = src; + } + + public function GetAnimation() + { + for (var i = 0; i < seqLength; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + RecursePieces(src, i + 1, 0, new Matrix()); + } + } + + protected function RecursePieces(graphic:MovieClip, frame, depth, parentMatrix:Matrix) + { + //_strace(depth+" "+graphic.name+" frame:"+frame); + + var mat:Matrix = graphic.transform.matrix.clone(); + mat.concat(parentMatrix); + + var currentPieces:Array = []; + + var allChildren:Array = Utils.GetChildren(graphic); + for (var i = 0; i < allChildren.length; i++) + { + if (!allChildren[i].visible) continue; + if (allChildren[i] is MovieClip) + { + if (AnimatedSkeletonGenerator.IsFullPiece(src, graphic, allChildren[i])) + { + currentPieces.push(allChildren[i]); + } else { + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + currentPieces.splice(0); + + depth = RecursePieces(allChildren[i], frame, depth, mat.clone()); + } + } else { + currentPieces.push(allChildren[i]); + } + } + + depth = GeneratePieceForClips(currentPieces, depth, frame, mat.clone()); + return depth; + } + + protected function GeneratePieceForClips(clips:Array, depth, frame, parentMatrix:Matrix) + { + if (clips.length > 0) + { + var l = clips.length; + var bounds:Rectangle = null; + + var invertMatrix:Matrix = clips[0].transform.matrix.clone(); + invertMatrix.invert(); + var i; + var m:Matrix; + var useMatrix:Array = []; + for (i = 0; i < clips.length; i++) + { + if (i == 0) + { + m = new Matrix(); + } else { + m = clips[i].transform.matrix.clone(); + m.concat(invertMatrix); + } + + var r:Rectangle = Utils.GetAccurateBounds(clips[i]); + Utils.TransformRect(r, m); + if (bounds == null) + { + bounds = r.clone(); + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.top < bounds.top) bounds.top = r.top; + if (r.right > bounds.right) bounds.right = r.right; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + + useMatrix.push(m); + } + + Utils.ScaleRect(bounds, gen.Def.scale); + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(Math.max(1, bounds.width), Math.max(1,bounds.height), true, 0x0); + + for (i = 0; i < clips.length; i++) + { + m = useMatrix[i]; + m.scale(gen.Def.scale, gen.Def.scale); + m.translate(-bounds.left, -bounds.top); + var ct:ColorTransform = clips[i] is Shape ? clips[i].parent.transform.colorTransform : clips[i].transform.colorTransform; + bd.draw(clips[i], m, ct, null, null, true); + } + + var center:Point = new Point(-bounds.left, -bounds.top); + + var piece:Piece = library.GetPieceFromBitmapData(bd, clips[0].parent.name, center); + if (piece) + { + var mat:Matrix = new Matrix(1 / gen.Def.scale, 0, 0, 1 / gen.Def.scale, center.x - piece.CenterPoint.x, center.y - piece.CenterPoint.y); + mat.concat(clips[0].transform.matrix); + mat.concat(parentMatrix); + + //mat.a /= exporter.Upscale; + //mat.d /= exporter.Upscale; + + var pieceSequence:PieceSequence = GetPieceSequence(piece, frame, clips[0], mat, depth); + var info:PieceFrameInfo = pieceSequence.GetFrame(frame); + if (info) + { + info.Present = true; + + info.Transform = mat; + + + + info.Depth = depth; + depth++; + } + } + } + return depth; + } + + protected function GetPieceSequence(piece:Piece, frame, clip:DisplayObject, newTransform:Matrix, newDepth) + { + if (this.pieces.indexOf(piece) == -1) this.pieces.push(piece); + var options:Array = []; + var i; + for (i in pieceSequences) + { + if (pieceSequences[i].GetPiece() == piece) + { + var frameInfo:PieceFrameInfo = pieceSequences[i].GetFrame(frame); + if (frameInfo && !frameInfo.Present) + { + if (pieceSequences[i].CheckMatches(clip)) + { + return pieceSequences[i]; + } else { + options.push(pieceSequences[i]); + } + } + } + } + + if (options.length == 0) + { + var s:PieceSequence = new PieceSequence(piece, seqLength); + piece.AddUse(seq); + pieceSequences.push(s); + return s; + } + + var scores:Array = []; + for (i = 0; i < options.length; i++) + { + var score = 0; + if (frame > 1) + { + var prevInfo:PieceFrameInfo = options[i].GetFrame(frame - 1); + if (prevInfo && prevInfo.Present) + { + score = ComputeTransformScore(prevInfo.Transform, prevInfo.Depth, newTransform, newDepth); + } + } + scores.push(score); + } + var sorted:Array = scores.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + return options[sorted[0]]; + } + + protected function ComputeTransformScore(transformA:Matrix, depthA, transformB:Matrix, depthB, posVal = 1, scaleVal = 15, rotVal = 20, depthVal = 10) + { + var deltaPos = Point.distance(new Point(transformA.tx, transformA.ty), new Point(transformB.tx, transformB.ty)); + deltaPos /= gen.Def.scale; + + var partsA = Utils.Decompose(transformA); + var partsB = Utils.Decompose(transformB); + + var rotA = partsA.rot; + var rotB = partsB.rot; + var deltaRot = Utils.GetAngleDiffAbs(rotA, rotB); + + var deltaScaleX = partsA.sx / partsB.sx; + if (deltaScaleX < 1) deltaScaleX = 1 / deltaScaleX; + var deltaScaleY = partsA.sy / partsB.sy; + if (deltaScaleY < 1) deltaScaleY = 1 / deltaScaleY; + var deltaScale = Math.max(deltaScaleX, deltaScaleY); + + var deltaDepth = Math.abs(depthA - depthB); + + return deltaPos * posVal + (deltaScale - 1) * scaleVal + deltaRot * rotVal + deltaDepth * depthVal; + } + + public static var ONLYCOMBINEADJACENT = true; + + protected function CombinePieces() + { + var i, j, info:PieceFrameInfo, index; + var sequenceByPresent = {}; + for (i in pieceSequences) + { + var str = ""; + for (j = 0; j < length; j++) + { + info = pieceSequences[i].GetFrame(j + 1); + str += (info && info.Present) ? "1" : "0"; + } + if (!(str in sequenceByPresent)) + { + sequenceByPresent[str] = []; + } + sequenceByPresent[str].push(pieceSequences[i]); + } + + for (var presentStr in sequenceByPresent) + { + var all:Array = sequenceByPresent[presentStr]; + + var firstFrame = ("" + presentStr).indexOf("1") + 1; + + var depths:Array = []; + for (i = 0; i < all.length; i++) + { + depths.push(all[i].GetFrame(firstFrame).Depth); + } + var sorted:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var groups:Array = []; + var lastGroup:Array = null; + for (i = 0; i < all.length; i++) + { + index = sorted[i]; + if (ONLYCOMBINEADJACENT) + { + if (lastGroup != null && SequenceMatches(lastGroup[0], all[index])) + { + lastGroup.push(all[index]); + } else { + lastGroup = []; + groups.push(lastGroup); + lastGroup.push(all[index]); + } + } else { + var foundGroup = false; + for (j in groups) + { + if (SequenceMatches(groups[j][0], all[index])) + { + groups[j].push(all[index]); + foundGroup = true; + break; + } + } + if (!foundGroup) + { + var g:Array = []; + g.push(all[index]); + groups.push(g); + } + } + } + } + + var p:Piece; + for (i in groups) + { + // recovering the original pieces... + // for now: render the bitmaps? (one will be transformed... but it would be transformed anyways, right?) + var group:Array = groups[i]; + if (group.length > 1) + { + var origSeq:PieceSequence = group[0]; + var invert:Matrix; + var firstPresent = null; + for (j = 0; j < length; j++) + { + info = origSeq.GetFrame(j + 1); + if (info && info.Present) + { + firstPresent = j + 1; + invert = info.Transform.clone(); + invert.invert(); + break; + } + } + var bounds:Rectangle = null; + var transforms:Array = []; + for (j = 0; j < group.length; j++) + { + p = group[j].GetPiece(); + p.RemoveUse(seq); + var m:Matrix = new Matrix(); + if (j > 0) + { + //m.translate(-group[j].CenterPoint.x, -group[j].CenterPoint.y); + m.concat(invert); + m.concat(group[j].GetFrame(firstPresent).Transform); + //m.translate(origSeq.CenterPoint.x, origSeq.CenterPoint.y); + } + var r:Rectangle = p.FullData.rect.clone(); + Utils.TransformRect(r, m); + + if (bounds == null) + { + bounds = r; + } else { + if (r.left < bounds.left) bounds.left = r.left; + if (r.right > bounds.right) bounds.right = r.right; + if (r.top < bounds.top) bounds.top = r.top; + if (r.bottom > bounds.bottom) bounds.bottom = r.bottom; + } + transforms.push(m); + } + Utils.RoundRect(bounds); + var bd:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + for (j = 0; j < group.length; j++) + { + transforms[j].translate(-bounds.left, -bounds.top); + bd.draw(group[j].GetPiece().FullData, transforms[j], null, null, null, true); + } + + p = library.GetPieceFromBitmapData(bd, "CombinedPiece"); + var seq:PieceSequence = new PieceSequence(p, seqLength); + p.AddUse(seq); + seq.CopyTransformsFrom(origSeq, group[group.length - 1].GetFrame(firstPresent).Depth); + + this.pieceSequences.push(seq); + + this.pieces.push(p); + } + } + + for (i in groups) + { + if (groups[i].length > 1) + { + for (j in groups[i]) + { + index = this.pieceSequences.indexOf(groups[i][j]); + if (index == -1) + { + throw new Error("huh?"); + } else { + pieceSequences.splice(index, 1); + } + } + } + } + + + for (i = 0; i < pieces.length; i++) + { + if (pieces[i].GetUses(seq) == 0) + { + pieces.splice(i, 1); + i--; + } + } + + } + + protected function SequenceMatches(a:PieceSequence, b:PieceSequence) + { + var relative:Matrix = null; + for (var i = 0; i < length; i++) + { + var infoA:PieceFrameInfo = a.GetFrame(i + 1); + var infoB:PieceFrameInfo = b.GetFrame(i + 1); + if (infoA && infoB && infoA.Present && infoB.Present) + { + var m:Matrix = Utils.GetTransform(infoA.Transform, infoB.Transform); + if (relative == null) + { + relative = m; + } else { + if (ComputeTransformScore(relative, 0, m, 0, 4, 15, 5, 0) > 4) return false; + } + } + } + return true; + } + + public function ProduceFrame(frame, excludeNames:Array = null):MovieClip + { + var i; + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + var m:MovieClip = new MovieClip(); + for (i = 0; i < sorts.length; i++) + { + var ps:PieceSequence = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + var b:Bitmap = new Bitmap(p.FullData); + + var mat:Matrix = new Matrix(); + mat.translate(-p.CenterPoint.x, -p.CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + //b.smoothing = true; + b.transform.matrix = mat; + + m.addChild(b); + } + } + return m; + } + + public function ProduceFrameBitmapData(frame, excludeNames:Array = null) + { + var ps:PieceSequence; + var r:Rectangle = null; + var i; + var mat:Matrix; + for (i in pieceSequences) + { + ps = pieceSequences[i]; + var frameInfo:PieceFrameInfo = ps.GetFrame(frame); + if (frameInfo && frameInfo.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var piece:Piece = ps.GetPiece(); + var bounds:Rectangle = piece.FullData.rect; + bounds.x -= piece.CenterPoint.x; + bounds.y -= piece.CenterPoint.y; + mat = frameInfo.Transform.clone(); + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + Utils.TransformRect(bounds, mat); + + if (r == null) + { + r = bounds; + } else { + if (bounds.left < r.left) r.left = bounds.left; + if (bounds.top < r.top) r.top = bounds.top; + if (bounds.right > r.right) r.right = bounds.right; + if (bounds.bottom > r.bottom) r.bottom = bounds.bottom; + } + + } + } + + if (r == null) { + return {data:new BitmapData(1, 1, true, 0x0),center_point:new Point(0, 0)}; + } + + Utils.RoundRect(r); + var bd:BitmapData; + try { + bd = new BitmapData(Math.min(512, r.width), Math.min(512, r.height), true, 0x0); + } catch (e){ + //_strace("failed to create bitmap data"); + } + + var depths:Array = []; + for (i = 0; i < pieceSequences.length; i++) + { + depths.push(pieceSequences[i].GetFrame(frame).Depth); + } + + var sorts:Array = depths.sort(Array.NUMERIC | Array.RETURNINDEXEDARRAY); + + for (i = 0; i < sorts.length; i++) + { + ps = pieceSequences[sorts[i]]; + var info:PieceFrameInfo = ps.GetFrame(frame); + if (info && info.Present && (excludeNames == null || excludeNames.indexOf(ps.GetPiece().Name) == -1)) + { + var p:Piece = ps.GetPiece(); + + mat = new Matrix(); + mat.translate(-ps.GetPiece().CenterPoint.x, -ps.GetPiece().CenterPoint.y); + mat.concat(info.Transform); + + //mat.scale(1 / exporter.Upscale, 1 / exporter.Upscale); + + mat.translate(-r.left, -r.top); + + bd.draw(p.FullData, mat, null, null, null, true); + } + } + return {data:bd,center_point:new Point(-r.left, -r.top)}; + } +} diff --git a/flash/generator/AnimatedSpriteGenerator.as b/flash/generator/AnimatedSpriteGenerator.as new file mode 100644 index 0000000..24de0bd --- /dev/null +++ b/flash/generator/AnimatedSpriteGenerator.as @@ -0,0 +1,117 @@ +package generator +{ + import flash.display.*; + import flash.geom.*; + import frame.*; + import job.*; + import util.*; + + public class AnimatedSpriteGenerator implements IFramesSource + { + private var src:MovieClip; + private var def:GraphicExportDef; + private var sequences:Array = new Array(); // [[AnimatedSpriteFrame]] + private var callback; + public function GetFrames():Array + { + var ret:Array = []; + for (var i in sequences) + { + ret = ret.concat(sequences[i].map(function(spriteFrame:AnimatedSpriteFrame, i, arr) { return spriteFrame.info; })); + } + return ret; + } + + public function GetData() + { + return { + scale:def.scale, + sequences:sequences.map( + function(s:Array, i, sArr) + { + return { + frames: s.map( + function(f:AnimatedSpriteFrame, i, fArr) + { + var r = {x:f.info.rect.x, y:f.info.rect.y, w:f.info.rect.width, h:f.info.rect.height}; + var c = {x:f.offset.x, y:f.offset.y}; + return {rect:r, center:c, resource:f.info.sheetIndex}; + } + ) + }; + } + ) + }; + } + + public function AnimatedSpriteGenerator(src:MovieClip, def:GraphicExportDef) + { + this.src = src; + this.def = def; + } + + public function Go(callback) + { + this.callback = callback; + for (var i = 0; i < src.totalFrames; i++) + { + Utils.WeirdGotoFrame(src, i + 1); + Utils.RecursivelyStop(src); + + for (var j = 0; j < src.numChildren; j++) + { + var c = src.getChildAt(j); + if (c is MovieClip) + { + sequences.push(GetAnimation(c, i)); + break; + } + } + } + + callback(true); + } + + private function GetAnimation(m:MovieClip, seq:int):Array + { + var ret:Array = new Array(); + for (var i = 0; i < m.totalFrames; i++) + { + Utils.WeirdGotoFrame(m, i + 1); + Utils.RecursivelyStop(m); + + var bounds:Rectangle = Utils.GetAccurateBounds(m, new Matrix(def.scale, 0, 0, def.scale)); + var frameBounds:Rectangle = new Rectangle(def.padding, def.padding, bounds.width, bounds.height); + + var drawMatrix:Matrix = new Matrix(def.scale, 0, 0, def.scale, -bounds.left + def.padding, -bounds.top + def.padding); + + var b:BitmapData = new BitmapData(bounds.width + def.padding * 2, bounds.height + def.padding * 2, true, 0x0); + b.drawWithQuality(m, drawMatrix, null, null, frameBounds, false, StageQuality.BEST); + + var info:FrameInfo = new FrameInfo(b, drawMatrix, bounds); + + var frameInfo:AnimatedSpriteFrame = new AnimatedSpriteFrame(); + frameInfo.info = info; + frameInfo.sequence = seq; + frameInfo.frame = i; + frameInfo.offset = new Point(-bounds.left + def.padding, -bounds.right + def.padding); + + ret.push(frameInfo); + } + + return ret; + } + } +} + +class AnimatedSpriteFrame +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + + public var info:FrameInfo; + public var sequence:int = 0; + public var frame:int = 0; + public var offset:Point = new Point(); +} diff --git a/flash/job/GraphicExportDef.as b/flash/job/GraphicExportDef.as new file mode 100644 index 0000000..1b9aff3 --- /dev/null +++ b/flash/job/GraphicExportDef.as @@ -0,0 +1,161 @@ +package job +{ + import flash.utils.*; + import flash.display.*; + import flash.system.LoaderContext; + import flash.events.*; + import by.blooddy.crypto.*; + import flash.system.SecurityDomain; + import frame.*; + import util.*; + import generator.*; + + public class GraphicExportDef + { + public const TYPE_SPRITES = 1; + public const TYPE_SKELETAL = 2; + + private var _exportType:int = 1; + public function get exportType():int { return _exportType; } + + private var _className:String = null; + public function get className():String { return _className; } + + private var _name:String = null; + public function get name():String { return _name; } + + private var _valid:Boolean = false; + public function get valid():Boolean { return _valid; } + + private var _padding:int = 0; + public function get padding():int { return _padding; } + + private var _scale:Number = 0; + public function get scale():Number { return _scale; } + + private var input:ByteArray; + private var inputLoader:Loader = null; + + private var parentJob:Job = null; + + private var callback = null; + + private var index:int = 0; + + public function GraphicExportDef(parentJob:Job, details, index:int) + { + this.parentJob = parentJob; + this.index = index; + if (!details.hasOwnProperty("type") || + !details.hasOwnProperty("name") || + !details.hasOwnProperty("input") || + !details.hasOwnProperty("class_name")) + { + Fail("graphic export is missing a required class_name, name, type, or input"); + return; + } + _exportType = parseInt(details.type); + _name = "" + details.name; + _className = "" + details.class_name; + input = Base64.decode("" + details.input); + _padding = details.hasOwnProperty("padding") ? parseInt(details.padding) : 0; + _scale = details.hasOwnProperty("scale") ? parseFloat(details.scale) : 1; + _valid = true; + } + + public function Fail(err:String) + { + parentJob.FailMessage("(" + index + ")" + err); + _valid = false; + if (callback != null) callback(); + } + + public function Go(callback) + { + this.callback = callback; + + inputLoader = new Loader(); + inputLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoaderComplete); + inputLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderError); + var context:LoaderContext = new LoaderContext(); + context.allowCodeImport = true; + inputLoader.loadBytes(input, context); + } + + private var frames:IFramesSource = null; + + private function LoaderComplete(e) + { + try + { + var classDef = e.target.applicationDomain.getDefinition(className); + if (classDef == null) + { + Fail("didn't contain a definition for " + className); + return; + } + + var clip = new classDef(); + if (!(clip is MovieClip)) + { + Fail(className + " wasn't a movieclip"); + } + + Utils.RecursivelyStop(clip); + + frames = null; + + switch (exportType) + { + case TYPE_SPRITES: + frames = new AnimatedSpriteGenerator(clip, this); + break; + case TYPE_SKELETAL: + frames = new AnimatedSkeletonGenerator(clip, this); + break; + } + + if (frames == null) + { + Fail("invalid export type: " + exportType); + return; + } + + frames.Go(FramesDone); + + } catch (e) + { + Exporter.Instance.Print(e.getStackTrace()); + } + } + + private function FramesDone(success) + { + if (!success) + { + Fail("couldn't get source frames"); + return; + } + Done(); + } + + private function LoaderError(e) + { + Fail("couldn't load input: " + e.toString()); + } + public function Done() + { + this.callback(); + } + + public function GetFrames():Array + { + return frames.GetFrames(); + } + + public function GetData() + { + return frames.GetData(); + } + } +} diff --git a/flash/job/Job.as b/flash/job/Job.as new file mode 100644 index 0000000..fc617db --- /dev/null +++ b/flash/job/Job.as @@ -0,0 +1,158 @@ +package job +{ + import flash.utils.*; + import flash.geom.*; + import flash.display.*; + import com.adobe.images.PNGEncoderWithAlpha; + import frame.*; + import util.*; + + public class Job + { + private var callback; + + private var id:int; + private var name:String; + + private var details; + + private var graphics:Array = new Array(); + + public function GetID():int { return this.id; } + public function Job(id:int, graphicsDetails:Array) + { + this.id = id; + for (var i in graphicsDetails) + { + var graphic:GraphicExportDef = new GraphicExportDef(this, graphicsDetails[i], i); + if (graphic.valid) + { + graphics.push(graphic); + } + } + Exporter.Instance.Trace("new job: " + id); + } + public function FailMessage(err:String) + { + Exporter.Instance.Print("Failure: job " + id + ": " + err); + } + + public function WarnMessage(err:String) + { + Exporter.Instance.Print("Warning: job " + id + ": " + err); + } + + private function Fail(err:String) + { + FailMessage(err); + callback(); + } + + private var goIndex = -1; + public function Go(callback) + { + this.callback = callback; + + goIndex = -1; + + CheckNextGraphic(); + } + + private function CheckNextGraphic() + { + goIndex++; + if (goIndex < graphics.length) + { + graphics[goIndex].Go(CheckNextGraphic); + } + else + { + Pack(); + } + } + + private var allFrames:Array; //[FrameInfo] + private var packer:FramePacker; + private function Pack() + { + allFrames = new Array(); + for (var i in graphics) + { + if (graphics[i].valid) + { + allFrames = allFrames.concat(graphics[i].GetFrames()); + } + } + packer = new FramePacker(allFrames); + packer.Pack(PackDone); + } + + private var sheets:Array; //[BitmapData] + private var sheetBytes:Array; //[ByteArray] + + private function PackDone(success) + { + if (!success) + { + Fail("couldn't pack exported frames to sheets"); + return; + } + + var i; + var sheet:BitmapData; + + sheets = new Array(); + sheetBytes = new Array(); + var sheetAllocators:Array = packer.GetSheets(); + for (i in sheetAllocators) + { + var allocator:RectanglePacker = sheetAllocators[i]; + sheet = new BitmapData(allocator.width, allocator.height, true, 0x0); + sheets.push(sheet); + } + for (i in allFrames) + { + var frameInfo:FrameInfo = allFrames[i]; + sheet = sheets[frameInfo.sheetIndex]; + sheet.copyPixels(frameInfo.frameData, frameInfo.frameData.rect, frameInfo.rect.topLeft); + } + for (i in sheets) + { + sheetBytes[i] = PNGEncoderWithAlpha.encode(sheets[i]); + } + + Done(); + } + + public function Done() + { + Exporter.Instance.Trace("Job.Done() " + id); + this.callback(); + } + + public function GetResources():Array //[ByteArray] + { + return sheetBytes; + } + + public function GetData() + { + var ret = {}; + for (var i in graphics) + { + if (graphics[i].valid) + { + if (ret[graphics[i].name] !== undefined) + { + WarnMessage("two graphics with same name: " + graphics[i].name); + } + else + { + ret[graphics[i].name] = graphics[i].GetData(); + } + } + } + return ret; + } + } +} diff --git a/flash/skeletal/Piece.as b/flash/skeletal/Piece.as new file mode 100644 index 0000000..414b30a --- /dev/null +++ b/flash/skeletal/Piece.as @@ -0,0 +1,177 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + import frame.FrameInfo; + import util.*; + + public class Piece + { + protected var size:Point; + protected var frameInfo:FrameInfo; + protected var compareData:BitmapData; + + protected var centerPoint:Point; + public function get CenterPoint():Point { return centerPoint; } + + public function get FullData():BitmapData { return frameInfo == null ? null : frameInfo.frameData; } + + public function get Frame():FrameInfo { return frameInfo; } + + protected var valid = false; + public function get Valid() { return valid; } + + public var Name:String = null; + + protected var usesBySequence = {}; + public function AddUse(sequence) + { + if (!(sequence in usesBySequence)) + { + usesBySequence[sequence] = 0; + } + usesBySequence[sequence]++; + } + + public function RemoveUse(sequence) + { + if (sequence in usesBySequence && usesBySequence[sequence] > 0) + { + usesBySequence[sequence]--; + } + } + + public function GetUses(sequence) + { + return (sequence in usesBySequence) ? usesBySequence[sequence] : 0; + } + + public function get TotalUses() + { + var count = 0; + for (var s in usesBySequence) + { + count += usesBySequence[s]; + } + return count; + } + + // returns the center point + public function InitFromClip(clip:DisplayObject, upscale:Number = 1):Point + { + var bounds:Rectangle = Utils.GetAccurateBounds(clip); + + size = new Point(bounds.width, bounds.height); + + valid = bounds.width > 0 && bounds.height > 0; + if (valid) + { + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(upscale, upscale); + + Utils.TransformRect(bounds, m); + Utils.RoundRect(bounds); + + m.translate(-bounds.left, -bounds.top); + + var fullData:BitmapData = new BitmapData(bounds.width, bounds.height, true, 0x0); + fullData.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + frameInfo = new FrameInfo(fullData, m, null); + + compareData = GenerateCompareData(clip); + + centerPoint = new Point(-bounds.left, -bounds.top); + return centerPoint; + } + return null; + } + + public function InitFromBitmapData(bd:BitmapData, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + valid = true; + size = new Point(bd.width, bd.height); + + frameInfo = new FrameInfo(bd, null, null); + + compareData = bd.clone(); + + this.centerPoint = centerPoint; + } + + public function Matches(otherData:BitmapData, otherName) + { + + if (false && otherName != null && Name != null) + { + //This whole section fails to match things properly... + + var m = Name.match("^([^0-9]+)(\\d*)"); + var tempName = m ? m[1] : Name; + + var mo = otherName.match("^([^0-9]+)(\\d*)"); + var tempOtherName = mo ? mo[1] : otherName; + + return tempName == tempOtherName; + + + if (m) + { + if (otherName != m[1]) return false; + return true; + } + else + { + if (otherName != Name) return false; + return true; + } + } + + var threshold = 3; + var maxPixels = 0; + var result = compareData.compare(otherData); + if (result == 0) return true; + if (result is BitmapData) + { + var histo:Vector.> = (result as BitmapData).histogram(); + for (var i = 0; i < 4; i++) + { + var diff:Vector. = histo[i]; + // for some STUPID reason, if all the colors match but the alphas dont, it returns FFFFFF for the color portion... + // so DON'T compare the histogram for color channels up to 255 + var max = i == 4 ? 255 : 254; + for (var j = threshold; j < Math.min(max, diff.length); j++) + { + if (diff[j] > maxPixels) + { + return false; + } + } + } + return true; + } + return false; + } + + public static function GenerateCompareData(clip:DisplayObject):BitmapData + { + var scale = 1; + + var quickBounds:Rectangle = clip.getBounds(clip); + var orig:Rectangle = quickBounds.clone(); + if (quickBounds.width == 0 || quickBounds.height == 0) return null; + Utils.ScaleRect(quickBounds, scale); + Utils.RoundRect(quickBounds); + + var m:Matrix = clip is Shape ? clip.transform.matrix.clone() : new Matrix(); + m.scale(scale, scale); + m.translate(-quickBounds.left, -quickBounds.top); + + var data:BitmapData = new BitmapData(quickBounds.width, quickBounds.height, true, 0x0); + data.draw(clip, m, clip is Shape && clip.parent ? clip.parent.transform.colorTransform : clip.transform.colorTransform, null, null, true); + + return data; + } + } +} diff --git a/flash/skeletal/PieceFrameInfo.as b/flash/skeletal/PieceFrameInfo.as new file mode 100644 index 0000000..3cfffe6 --- /dev/null +++ b/flash/skeletal/PieceFrameInfo.as @@ -0,0 +1,10 @@ +package skeletal +{ + import flash.geom.*; + public class PieceFrameInfo + { + public var Present = false; + public var Transform:Matrix = null; + public var Depth = null; + } +} diff --git a/flash/skeletal/PieceLibrary.as b/flash/skeletal/PieceLibrary.as new file mode 100644 index 0000000..0c034f9 --- /dev/null +++ b/flash/skeletal/PieceLibrary.as @@ -0,0 +1,154 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.Point; + import flash.utils.*; + + public class PieceLibrary + { + protected var pieces:Array = []; + + public function Reset() + { + pieces.splice(0); + } + + private function GetArtistGivenName(clipName:String):String + { + if (clipName.match(/instance\d+/)) + { + return null; + } + return clipName; + } + + private function GetNextAvailableName(artistName:String):String + { + if (artistName == null) return null; + if (artistName.match("^instance\\d+$")) return null; + + var maxNameCount = 0; + for (var i in pieces) + { + if (pieces[i].Name != null) + { + var m = pieces[i].Name.match(new RegExp("^" + artistName + "(\\d+)?$")); + if (m) + { + maxNameCount = Math.max(maxNameCount, m[1] == undefined ? 1 : (Number(m[1]) + 1)); + } + } + } + return artistName + (maxNameCount == 0 ? "" : maxNameCount); + } + + public function GetPieceFromClip(clip:DisplayObject, outCenterPoint:Point, upscale:Number = 1) + { + var piece:Piece = GetExistingPiece(Piece.GenerateCompareData(clip), clip.name); + if (piece != null) return piece; + + piece = new Piece(); + var center:Point = piece.InitFromClip(clip, upscale); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(clip.name); + + pieces.push(piece); + outCenterPoint.x = center.x; + outCenterPoint.y = center.y; + return piece; + } + + return null; + } + + private function GetExistingPiece(compareData:BitmapData, artistName:String) + { + if (compareData == null) return null; + + for (var i in pieces) + { + if (pieces[i].Matches(compareData, artistName)) + { + if (pieces[i].Name == null) + { + pieces[i].Name = GetNextAvailableName(artistName); + } + return pieces[i]; + } + } + + return null; + } + + public function GetPieceFromBitmapData(bd:BitmapData, pieceName:String, centerPoint:Point = null) + { + if (centerPoint == null) centerPoint = new Point(0, 0); + + var piece:Piece = GetExistingPiece(bd, pieceName); + if (piece != null) return piece; + + piece = new Piece(); + piece.InitFromBitmapData(bd, centerPoint); + if (piece.Valid) + { + piece.Name = GetNextAvailableName(pieceName); + pieces.push(piece); + return piece; + } + + return null; + } + + public function Debug() + { + var nextX = 0; + for (var i = 0; i < pieces.length; i++) + { + if (pieces[i].TotalUses > 0) + { + var b:Bitmap = new Bitmap(pieces[i].FullData); + b.scaleX = b.scaleY = 1; + b.x = nextX; + nextX += b.width; + } + } + } + + public function get NumUsedPieces() + { + var count = 0; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + count++; + } + } + return count; + } + + public function GetAllUsedPieces():Array + { + var ret:Array = []; + for (var i in this.pieces) + { + if (pieces[i].TotalUses > 0) + { + ret.push(pieces[i]); + } + } + return ret; + } + + public function EnsureAllUsedPiecesHaveNames() + { + var index = 0; + var used:Array = GetAllUsedPieces(); + for (var i in used) + { + if (used[i].Name == null) used[i].Name = "UnknownPiece" + (index++); + } + } + } +} diff --git a/flash/skeletal/PieceSequence.as b/flash/skeletal/PieceSequence.as new file mode 100644 index 0000000..0b1b97f --- /dev/null +++ b/flash/skeletal/PieceSequence.as @@ -0,0 +1,62 @@ +package skeletal +{ + import flash.display.*; + import flash.geom.*; + public class PieceSequence + { + protected var piece:Piece; + protected var overridePiece:Piece; + public function GetOriginalPiece():Piece { return piece; } + public function GetPiece():Piece { return overridePiece ? overridePiece : piece; } + public function SetOverridePiece(p:Piece) { this.overridePiece = p; } + + public var Export:Boolean = true; + + //protected var centerPoint:Point; + //public function get CenterPoint():Point { return centerPoint; } + + public function GetFrame(frameNum):PieceFrameInfo + { + if (frameNum < 1 || frameNum > frames.length) return null; + return frames[frameNum - 1]; + } + + public function CopyTransformsFrom(other:PieceSequence, atDepth = null) + { + if (other.frames.length == this.frames.length) + { + for (var i = 0; i < frames.length; i++) + { + this.frames[i].Present = other.frames[i].Present; + if (other.frames[i].Present) + { + this.frames[i].Transform = other.frames[i].Transform.clone(); + this.frames[i].Depth = (atDepth == null) ? other.frames[i].Depth : atDepth; + } + } + } + } + + protected var frames:Array = []; + public function PieceSequence(piece:Piece, length) //, centerPoint:Point) + { + this.piece = piece; + //this.centerPoint = centerPoint; + for (var i = 0; i < length; i++) + { + frames.push(new PieceFrameInfo()); + } + } + + // clip matching info + public var BaseClip:DisplayObject = null; + public var Name = null; + + public function CheckMatches(clip:DisplayObject) + { + if (BaseClip != null && clip == BaseClip) return true; + if (Name != null && clip.name == null) return true; + return false; + } + } +} diff --git a/flash/util/RectangleNode.as b/flash/util/RectangleNode.as new file mode 100644 index 0000000..6f31e44 --- /dev/null +++ b/flash/util/RectangleNode.as @@ -0,0 +1,178 @@ +package util { + import flash.geom.Rectangle; + + public class RectangleNode + { + public var Left:RectangleNode = null; + public var Right:RectangleNode = null; + public var Rect:Rectangle = null; + public var InUse:Boolean = false; + public var Removed:Boolean = false; + public var Parent:RectangleNode = null; + public var AllocationID = 0; + public var Host:RectanglePacker= null; + public var MinAllocationID = 0; + public var NodeID; + public static var NextNodeID = 0; + + public var DontRemove = false; + + public var LastAccessTime = 0; + + public var Flags = []; + + public var UpdateTo:RectangleNode = null; + + /* + public function get Removed() + { + return _Removed; + } + + public function set Removed(r) + { + this._Removed = r; + } + + public function get Host():RectanglePacker + { + return _Host; + } + public function set Host(p:RectanglePacker) + { + this._Host = p; + + if (_Left && _Left.Host != p) + { + throw new Error("bad left host"); + } + if (_Right && _Right.Host != p) + { + throw new Error("bad right host"); + } + if (_Parent && _Parent.Host != p) + { + throw new Error("bad parent host"); + } + + } + + public function get Left():RectangleNode + { + return _Left; + } + public function set Left(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad left host"); + } + _Left = n; + } + public function get Right():RectangleNode + { + return _Right; + } + public function set Right(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad right host"); + } + _Right = n; + } + + public function get Parent():RectangleNode + { + return _Parent; + } + public function set Parent(n:RectangleNode) + { + if (n && n.Host != Host) + { + throw new Error("bad parent host"); + } + _Parent = n; + } + */ + public function get IsFreeSpace() + { + return Left == null && Right == null && !InUse; + } + public function UpdateLinksFromNode(node:RectangleNode) + { + if (node.Parent) + { + if (node.Parent.Left == node) + { + node.Parent.Left = this; + } + if (node.Parent.Right == node) + { + node.Parent.Right = this; + } + } + if (node.Left) + { + node.Left.Parent = this; + } + if (node.Right) + { + node.Right.Parent = this; + } + } + public function MakeFromNode(node:RectangleNode) + { + //_Host = node.Host; + Host = node.Host; + Left = node.Left; + Right = node.Right; + Parent = node.Parent; + AllocationID = node.AllocationID; + InUse = node.InUse; + MinAllocationID = node.MinAllocationID; + NodeID = node.NodeID; + Rect = node.Rect.clone(); + Removed = node.Removed; + DontRemove = node.DontRemove; + } + public function RectangleNode(x, y, w, h, host:RectanglePacker) + { + this.NodeID = NextNodeID++; + this.Host = host; + this.Rect = new Rectangle(x, y, w, h); + } + public function OutputJSON() + { + var node = {}; + node.rect = [this.Rect.left, this.Rect.top, this.Rect.width, this.Rect.height]; + node.in_use = InUse; + node.id = NodeID; + if (this.Left) node.left = this.Left.OutputJSON(); + if (this.Right) node.right = this.Right.OutputJSON(); + return node; + } + + public function ReadJSON(details) + { + details.new_node = this; + this.Rect = new Rectangle(details.rect[0], details.rect[1], details.rect[2], details.rect[3]); + this.Removed = false; + + this.InUse = details.in_use; + + if (details.hasOwnProperty("right")) + { + this.Right = new RectangleNode(0, 0, 0, 0, this.Host); + Right.ReadJSON(details.right); + Right.Parent = this; + } + if (details.hasOwnProperty("left")) + { + this.Left = new RectangleNode(0, 0, 0, 0, this.Host); + Left.ReadJSON(details.left); + Left.Parent = this; + } + } + } +} diff --git a/flash/util/RectanglePacker.as b/flash/util/RectanglePacker.as new file mode 100644 index 0000000..597d7fd --- /dev/null +++ b/flash/util/RectanglePacker.as @@ -0,0 +1,562 @@ +package util { + import flash.geom.*; + import flash.display.BitmapData; + import flash.display.MovieClip; + import flash.text.TextField; + import flash.events.*; + import flash.sampler.StackFrame; + + public class RectanglePacker + { + protected var w:int; + protected var h:int; + protected var root:RectangleNode; + public var NextAllocationID = 0; + + public function get width():int { return w; } + public function get height():int { return h; } + + public function RectanglePacker(w, h) + { + this.w = w; + this.h = h; + root = new RectangleNode(0, 0, w, h, this); + root.AllocationID = -1; + } + protected var area = 0; + + protected var testRender:MovieClip = new MovieClip(); + + public function GetRoot():RectangleNode + { + return root; + } + + public function GetLeafNodes():Array + { + return GetLeafNodesInternal(root); + } + + protected function GetLeafNodesInternal(n:RectangleNode):Array + { + if (n.InUse) return [n]; + var ret:Array = new Array(); + if (n.Left) ret = GetLeafNodesInternal(n.Left); + if (n.Right) ret = ret.concat(GetLeafNodesInternal(n.Right)); + return ret; + } + + public function GetUsedArea() + { + return area; + } + + public function get efficiency() + { + return area / (w * h); + } + + protected function RectCost(w, h) + { + if (w == 0 || h == 0) return 99999999; + return (Math.max(w, h) / Math.min(w, h)) * w * h; + } + + protected function EnumerateTree(r:RectangleNode = null, indent = "") + { + if (r == null) r = this.root; + var str = ""; + str += indent + r.NodeID + " r:" + r.Removed + " iu" + r.InUse + " ifs" + r.IsFreeSpace + " " + r.Rect.left + "," + r.Rect.top + " -> " + r.Rect.right + "," + r.Rect.bottom + "\n"; + if (r.Left) str += EnumerateTree(r.Left, indent + " "); + if (r.Right) str += EnumerateTree(r.Left, indent + " "); + return str; + } + + /* + * Remove a list of nodes from the tree. + * - fullyDestroy: if not set, the nodes will be reused as nodes representing the new empty space in the tree + * if set, the nodes will be duplicated as new objects to be inserted into the tree as blank space, + leaving the original objects intact (in case something still references them) + */ + public function RemoveNodes(nodes:Array, fullyDestroy = true) + { + + /* DEBUG CHECKS */ + /* + this.PerformDebugCheck(); + + var str = ""; + for (var i = 0; i < nodes.length; i++) + { + str += nodes[i].NodeID + "\n"; + } + + var orig = nodes.concat(); + + var strs = [str, EnumerateTree()]; + + RenderDetailsBox.StartTrack("PackRemoveTime"); + + for (var i = 0; i < nodes.length; i++) + { + var n:RectangleNode = nodes[i]; + if (n.Host != this) + { + throw new Error("bad host!"); + } + } + */ + /* END DEBUG CHECKS */ + + var i, n:RectangleNode, p:RectangleNode; + + // setup the Removed flag on every node that should be removed + // we also check at this time to see if any more nodes need to be removed, such as a parent of + // 2 removed nodes (we want to optimize the tree to get rid of completely empty subtrees) + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + if (n.Host == this) + { + n.Removed = true; + + if (n.InUse) + { + // sum up the total removed area + area -= n.Rect.width * n.Rect.height; + } + + if (n.Parent != null) + { + p = n.Parent; + // check and see if the current node's parent still has any valid children + if ((p.Left.IsFreeSpace || p.Left.Removed) && (p.Right.IsFreeSpace || p.Right.Removed)) + { + // all of the current nodes siblings are either being removed or are blank, so + // we can remove the parent too + if (p.Left.IsFreeSpace) + { + // the left child was empty space before, so we can remove it (if it wasn't + // empty space it is already being removed so it doesn't need to be added + // to the list) + if (nodes.indexOf(p.Left) == -1) nodes.push(p.Left); + } + if (p.Right.IsFreeSpace) + { + // the right child was empty space before, so we can remove it + if (nodes.indexOf(p.Right) == -1) nodes.push(p.Right); + } + if (p != root && nodes.indexOf(p) == -1) + { + // remove the parent node too (provided it isn't the root!) + nodes.push(p); + } + } + } + } + } + + // now we have an expanded list of all nodes that will actually be cut out to return an optimized tree, + // so go ahead and remove them + for (i = 0; i < nodes.length; i++) + { + n = nodes[i]; + + if (n.Parent != null) + { + // n is getting removed, so n.Parent may have some changes to its pointers (provided n.Parent is not + // also getting removed!) + p = n.Parent; + + if (!p.Removed) + { + if (p.Left && p.Right) + { + var newNode:RectangleNode; + if (p.Left.Removed && p.Right.Removed) + { + // both children were removed, but the parent wasn't, so the parent must be root + // (since we never remove the root) + if (p != root) + { + throw new Error("should be root"); + } + p.Left.Parent = null; + p.Right.Parent = null; + p.Left = null; + p.Right = null; + p.InUse = false; + } else if (!p.Left.Removed) { + // Right node removed, Left node not removed + if (!p.Left.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Right); + newNode.UpdateLinksFromNode(p.Right); + } + // Left node is used + p.Right.InUse = false; + p.Right.Left = null; + p.Right.Right = null; + p.Right.Removed = false; + } else { + throw new Error("should have been caught above!"); + } + } else { + // Left node removed, Right node not removed + if (!p.Right.IsFreeSpace) + { + if (fullyDestroy) + { + // duplicate the node representing empty space so the original node + // remains untouched + newNode = new RectangleNode(0, 0, 0, 0, this); + newNode.MakeFromNode(p.Left); + newNode.UpdateLinksFromNode(p.Left); + } + // Left node is used + //p.Left.Removed = true; + p.Left.InUse = false; + p.Left.Left = null; + p.Left.Right = null; + p.Left.Removed = false; + //p.Left.Parent = null; + } else { + throw new Error("should have been caught above!"); + } + } + } else { + // huh? how does n.Parent == p but p has no children? something went wrong + throw new Error("shouldn't have gotten here"); + } + } + } + //strs.push(EnumerateTree()); + } + } + + public function Insert(w, h, useInstead:RectangleNode = null):RectangleNode + { + + var node:RectangleNode = FindSizedNode(w, h, root); + + if (node == null) + { + //UHOH, texture full + return null; + } + area += w * h; + node.InUse = true; + + var splitVertFirstCost = 0; + if (w < node.Rect.width) + { + splitVertFirstCost = RectCost(node.Rect.width - w, node.Rect.height) + RectCost(w, node.Rect.height - h); + } + + var splitHorizFirstCost = 0; + if (h < node.Rect.height) + { + splitHorizFirstCost = RectCost(node.Rect.width - w, h) + RectCost(node.Rect.width, node.Rect.height - h); + } + + + + if (splitVertFirstCost <= splitHorizFirstCost) + { + node.Flags.push("SplitVertFirst"); + if (w < node.Rect.width) + { + node.Flags.push("SplitVert"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + if (h < node.Rect.height) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + } else { + node.Flags.push("SplitHorzFirst"); + if (h < node.Rect.height) + { + node.Flags.push("SplitVert"); + node.InUse = false; + SplitHoriz(node, h); + node.Left.InUse = true; + node = node.Left; + } + if (w < node.Rect.width) + { + node.Flags.push("SplitHorz"); + node.InUse = false; + // split node vertically + SplitVert(node, w); + node.Left.InUse = true; + node = node.Left; + } + } + NextAllocationID++; + if (useInstead) + { + useInstead.MakeFromNode(node); + useInstead.UpdateLinksFromNode(node); + useInstead.Flags = node.Flags; + node = useInstead; + node.Flags.push("UseInstead"); + } + + //if (!CheckOKNode(node)) node.Flags.push("BadNode"); + + return node; + } + public function CheckOKNode(n:RectangleNode, r:RectangleNode = null) + { + if (r == null) r = this.root; + if (n != r && r.InUse && n.Rect.intersection(r.Rect).size.length > 0) + { + var ancestor:RectangleNode = FindCommonNode(n, r); + throw new Error("bad node allocated!"); + return false; + } + var ok = true; + if (r.Left) ok = ok && CheckOKNode(n, r.Left); + if (r.Right) ok = ok && CheckOKNode(n, r.Right); + return ok; + } + + public function PerformDebugCheck() + { + DebugInternal(this.root); + } + + protected function DebugInternal(n:RectangleNode) + { + if (n.Host != this) + { + throw new Error("problem with host!"); + } + if (n.IsFreeSpace) + { + if (n.Left || n.Right) + { + throw new Error("shouldn't have children"); + } + } + if ((n.Left && !n.Right) || (n.Right && !n.Left)) + { + throw new Error("mismatched children"); + } + if (n.Left && n.Left.Parent != n) + { + throw new Error("left child has bad parent"); + } + if (n.Right && n.Right.Parent != n) + { + throw new Error("right child has bad parent"); + } + if (n.Parent && n.Parent.Left != n && n.Parent.Right != n) + { + throw new Error("problem with parent"); + } + if (n.Left) DebugInternal(n.Left); + if (n.Right) DebugInternal(n.Right); + } + + public function FindCommonNode(a:RectangleNode, b:RectangleNode) + { + var aHistory = []; + var bHistory = []; + while (a != null) + { + aHistory.push(a); + a = a.Parent; + } + while (b != null) + { + bHistory.push(b); + b = b.Parent; + } + var i = aHistory.length - 1; + var j = bHistory.length - 1; + var same = null; + while (i >= 0 && j >= 0) + { + if (aHistory[i] == bHistory[j]) + { + same = aHistory[i]; + } else { + break; + } + i--; + j--; + } + return same; + } + + public function TestRender() + { + while (testRender.numChildren > 0) + { + testRender.removeChildAt(0); + } + testRender.graphics.clear(); + TestRenderNode(root, testRender); + return testRender; + } + protected function TestRenderNode(n:RectangleNode, m:MovieClip) + { + var g:MovieClip = new MovieClip(); + m.addChild(g); + g.graphics.lineStyle(1, 0, 1); + if (n.Left != null) TestRenderNode(n.Left, m); + if (n.Left != null) TestRenderNode(n.Right, m); + if (n.InUse) + { + g.graphics.beginFill(0xFFFF00, 0.2); + } + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + if (n.InUse) + { + g.graphics.endFill(); + var t:TextField = new TextField(); + t.text = n.NodeID; + t.x = n.Rect.x + n.Rect.width / 2.0; + t.y = n.Rect.y + n.Rect.height / 2.0; + g.addChild(t); + g.addEventListener(MouseEvent.MOUSE_OVER, function(e){MouseOver(n,g,t);}); + g.addEventListener(MouseEvent.MOUSE_OUT, function(e){MouseOut(n,g,t);}); + } + + } + public function MouseOver(n:RectangleNode, g:MovieClip, t:TextField) + { + if (n.InUse) + { + //_trace(Math.round(n.LastAccessTime / 1000)); + } + var p:RectangleNode = n.Parent; + if (p) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(p.IsFreeSpace ? 0x0000FF : 0xFF0000, 0.4); + g.graphics.drawRect(p.Rect.x, p.Rect.y, p.Rect.width, p.Rect.height); + g.graphics.endFill(); + t.text = p.NodeID; + if (g.oldListener) g.removeEventListener(MouseEvent.CLICK, g.oldListener); + g.oldListener = function(e){MouseOver(p, g, t);}; + g.addEventListener(MouseEvent.CLICK, g.oldListener); + } + } + public function MouseOut(n:RectangleNode, g:MovieClip, t:TextField) + { + g.graphics.clear(); + g.graphics.lineStyle(1, 0, 1); + g.graphics.beginFill(0xFFFF00, 0.2); + g.graphics.drawRect(n.Rect.x, n.Rect.y, n.Rect.width, n.Rect.height); + g.graphics.endFill(); + t.text = n.NodeID; + } + protected function SplitVert(node:RectangleNode, leftWidth) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, leftWidth, node.Rect.height, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x + leftWidth, node.Rect.y, node.Rect.width - leftWidth, node.Rect.height, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function SplitHoriz(node:RectangleNode, topHeight) + { + node.Left = new RectangleNode(node.Rect.x, node.Rect.y, node.Rect.width, topHeight, this); + node.Left.AllocationID = NextAllocationID; + node.Left.Parent = node; + node.Right = new RectangleNode(node.Rect.x, node.Rect.y + topHeight, node.Rect.width, node.Rect.height - topHeight, this); + node.Right.AllocationID = NextAllocationID; + node.Right.Parent = node; + + //CheckOKNode(node.Left); + //CheckOKNode(node.Right); + } + protected function FindSizedNode(w, h, node:RectangleNode):RectangleNode + { + if (node.InUse) return null; + if (node.Rect.width >= w && node.Rect.height >= h) + { + if (node.Left != null && node.Right != null) + { + var t:RectangleNode = FindSizedNode(w, h, node.Left); + if (t != null) return t; + t = FindSizedNode(w, h, node.Right); + return t; + } else { + return node; + } + } + return null; + } + + public function LoadTree(details) + { + this.root = new RectangleNode(0, 0, 0, 0, this); + root.ReadJSON(details); + + this.NextAllocationID = 0; + this.area = 0; + + var queue:Array = new Array(); + queue.push(root); + while (queue.length > 0) + { + var node:RectangleNode = queue.shift(); + node.AllocationID = NextAllocationID; + node.MinAllocationID = NextAllocationID; + if (node.Left) queue.push(node.Left); + if (node.Right) queue.push(node.Right); + if (node.InUse) this.area += node.Rect.width * node.Rect.height; + } + NextAllocationID++; + } + + public function GetNodePath(node:RectangleNode) + { + var output:String = ""; + while (node != this.root) + { + output = (node == node.Parent.Left ? "l" : "r") + output; + node = node.Parent; + } + return output; + } + + public function GetNodeFromPath(path:String):RectangleNode + { + var node:RectangleNode = this.root; + for (var i = 0; i < path.length; i++) + { + if (!node) return null; + if (path.charAt(i) == "r") + { + node = node.Right; + } else { + node = node.Left; + } + } + return node; + } + } +} diff --git a/flash/util/Utils.as b/flash/util/Utils.as new file mode 100644 index 0000000..f792003 --- /dev/null +++ b/flash/util/Utils.as @@ -0,0 +1,389 @@ +package util +{ + import flash.display.*; + import flash.geom.*; + public class Utils + { + public static function GetChildren(clip:MovieClip):Array + { + var ret:Array = []; + for (var i = 0; i < clip.numChildren; i++) + { + ret.push(clip.getChildAt(i)); + } + return ret; + } + + /* + * angle difference + * (range -Math.PI to Math.PI) + */ + public static function GetAngleDiff(a, b) + { + var angleDiff = b - a; + + while (angleDiff > Math.PI) + { + angleDiff -= Math.PI * 2; + } + while (angleDiff < -Math.PI) + { + angleDiff += Math.PI * 2; + } + return angleDiff; + } + + /* + * angle difference + * (range 0 to Math.PI) + */ + public static function GetAngleDiffAbs(a, b) + { + var angleDiff = GetAngleDiff(a, b); + while (angleDiff < 0) + { + angleDiff += Math.PI * 2; + } + + if (angleDiff > Math.PI) + { + angleDiff = Math.PI * 2 - angleDiff; + } + + return angleDiff; + } + + public static function GetTransform(from:Matrix, to:Matrix) + { + var i:Matrix = from.clone(); + i.invert(); + var m:Matrix = to.clone(); + m.concat(i); + return m; + } + + public static function Decompose(m:Matrix) + { + var s:Point = ScaleFromMat(m); + m = m.clone(); + + var sxUnit = s.x >= 0 ? 1 : -1; + var syUnit = s.y >= 0 ? 1 : -1; + + m.scale(sxUnit, syUnit); + + //m.a /= sxUnit; + //m.d /= syUnit; + var rot = RotFromMat(m); + return {sx:s.x, sy:s.y, rot:rot}; + } + + public static function RotFromMat(m:Matrix) + { + return Math.atan2(-m.c, m.a); + } + + public static function ScaleFromMat(m:Matrix):Point + { + var xAxisX = m.a; + var xAxisY = m.c; + + var yAxisX = m.b; + var yAxisY = m.d; + + var sx = Math.sqrt(xAxisX * xAxisX + xAxisY * xAxisY); + if (m.a < 0) sx *= -1; + + var sy = Math.sqrt(yAxisX * yAxisX + yAxisY * yAxisY); + if (m.d < 0) sy *= -1; + + return new Point(sx, sy); + } + + public static function TransformRect(r:Rectangle, m:Matrix) + { + var p1:Point = new Point(r.left, r.top); + var p2:Point = new Point(r.right, r.top); + var p3:Point = new Point(r.left, r.bottom); + var p4:Point = new Point(r.right, r.bottom); + + p1 = m.transformPoint(p1); + p2 = m.transformPoint(p2); + p3 = m.transformPoint(p3); + p4 = m.transformPoint(p4); + + r.left = Math.min(p1.x, p2.x, p3.x, p4.x); + r.top = Math.min(p1.y, p2.y, p3.y, p4.y); + r.right = Math.max(p1.x, p2.x, p3.x, p4.x); + r.bottom = Math.max(p1.y, p2.y, p3.y, p4.y); + } + + public static function RoundRect(r:Rectangle) + { + r.left = Math.floor(r.left); + r.top = Math.floor(r.top); + r.right = Math.ceil(r.right); + r.bottom = Math.ceil(r.bottom); + } + + public static function ScaleRect(r:Rectangle, s) + { + r.left *= s; + r.top *= s; + r.right *= s; + r.bottom *= s; + } + + public static function RecursivelyStop(clip) + { + if (clip is MovieClip) + { + clip.stop(); + } + if (clip is DisplayObjectContainer) + { + for (var i = 0; i < clip.numChildren; i++) + { + RecursivelyStop(clip.getChildAt(i)); + } + } + } + + public static function WeirdGotoFrame(clip:MovieClip, frame) + { + var dir = clip.currentFrame > frame ? -1 : 1; + while (clip.currentFrame != frame) + { + RecurseDir(clip, dir); + } + } + + protected static function RecurseDir(clip:MovieClip, dir) + { + for (var i = 0; i < clip.numChildren; i++) + { + var child = clip.getChildAt(i); + if (child is MovieClip) + { + RecurseDir(child, dir); + } + } + if (dir == 1) + { + clip.nextFrame(); + } else { + clip.prevFrame(); + } + } + + protected static var tempSpace:BitmapData = null; + protected static var tempSpaceRect:Rectangle = new Rectangle(); + protected static var tempSpaceMatrix:Matrix = new Matrix(); + protected static var tempSpaceZero:Point = new Point(); + protected static var tempSpaceColorTransform:ColorTransform = new ColorTransform(0,0,0,0,0,0,0,255); + protected static var lastDrawOffset:Point = new Point(); + public static function GetAccurateBounds(clip:DisplayObject, useMatrix:Matrix = null):Rectangle + { + if (!tempSpace) tempSpace = new BitmapData(2048, 2048, true, 0x0); + + var oldPad = 0; + var padAmount = 5; + + var ret:Rectangle = new Rectangle(); + + var baseBounds:Rectangle = clip.getBounds(clip); + + var boundsClip:DisplayObject = null; + if (clip is DisplayObjectContainer) + { + boundsClip = (clip as DisplayObjectContainer).getChildByName("__bounds__"); + } + + if (boundsClip != null) + { + baseBounds = boundsClip.getBounds(clip); + } + + if (useMatrix) + { + TransformAABBRect(baseBounds, useMatrix); + } + + if (boundsClip != null) + { + return baseBounds; + } + + var minW = Math.pow(2, Math.ceil(Math.log(baseBounds.width + padAmount * 2) / Math.log(2))); + var minH = Math.pow(2, Math.ceil(Math.log(baseBounds.height + padAmount * 2) / Math.log(2))); + if (tempSpace == null) + { + tempSpace = new BitmapData(minW, minH, true, 0x0); + } + if (tempSpace.width < minW || tempSpace.height < minH) + { + tempSpace = new BitmapData(Math.max(tempSpace.width, minW), Math.max(tempSpace.height, minH), true, 0x0); + } + + var r:Rectangle = new Rectangle(); + + baseBounds.left = Math.floor(baseBounds.left); + baseBounds.right = Math.ceil(baseBounds.right); + + baseBounds.top = Math.floor(baseBounds.top); + baseBounds.bottom = Math.ceil(baseBounds.bottom); + + var i; + + var needsChecking = true; + while (needsChecking) + { + needsChecking = false; + r.left = baseBounds.left - padAmount; + r.right = baseBounds.right + padAmount; + + r.top = baseBounds.top - padAmount; + r.bottom = baseBounds.bottom + padAmount; + + ret = r.clone(); + + tempSpaceRect.x = tempSpaceRect.y = 0; + tempSpaceRect.width = tempSpace.width; + tempSpaceRect.height = tempSpace.height; + tempSpace.fillRect(tempSpaceRect, 0x0); + + tempSpaceMatrix.identity(); + if (useMatrix) + { + tempSpaceMatrix.a = useMatrix.a; + tempSpaceMatrix.b = useMatrix.b; + tempSpaceMatrix.c = useMatrix.c; + tempSpaceMatrix.d = useMatrix.d; + tempSpaceMatrix.tx = useMatrix.tx; + tempSpaceMatrix.ty = useMatrix.ty; + } + tempSpaceMatrix.translate(-r.left, -r.top); + + lastDrawOffset.x = -r.left; + lastDrawOffset.y = -r.top; + tempSpace.draw(clip, tempSpaceMatrix); + + tempSpaceRect.width = 1; + tempSpaceRect.height = r.height; + + var sideMovedIn = 0; + for (i = 0; i < r.width; i++) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.left++; + sideMovedIn++; + } + } + if (ret.left < baseBounds.left - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.width - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.x = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.right--; + } + } + if (ret.right > baseBounds.right + oldPad + 1 && sideMovedIn <= baseBounds.right + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + sideMovedIn = 0; + tempSpaceRect.width = r.width; + tempSpaceRect.height = 1; + tempSpaceRect.x = 0; + for (i = 0; i < r.height; i++) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.top++; + sideMovedIn++; + } + } + if (ret.top < baseBounds.top - oldPad - 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + + for (i = r.height - 1; i >= sideMovedIn; i--) + { + tempSpaceRect.y = i; + if (tempSpace.hitTest(tempSpaceZero, 1, tempSpaceRect)) + { + break; + } else { + ret.bottom--; + } + } + if (ret.bottom > baseBounds.bottom + oldPad + 1 && sideMovedIn <= baseBounds.bottom + oldPad + 1) + { + oldPad = padAmount; + padAmount += 20; + needsChecking = true; + continue; + } + } + return ret; + } + + public static function TransformAABBRect(r:Rectangle, m:Matrix) + { + var o1X = r.left; + var o1Y = r.top; + + var o2X = r.right; + var o2Y = r.top; + + var o3X = r.left; + var o3Y = r.bottom; + + var o4X = r.right; + var o4Y = r.bottom; + + var n1X = o1X * m.a + o1Y * m.c + m.tx; + var n1Y = o1X * m.b + o1Y * m.d + m.ty; + + var n2X = o2X * m.a + o2Y * m.c + m.tx; + var n2Y = o2X * m.b + o2Y * m.d + m.ty; + + var n3X = o3X * m.a + o3Y * m.c + m.tx; + var n3Y = o3X * m.b + o3Y * m.d + m.ty; + + var n4X = o4X * m.a + o4Y * m.c + m.tx; + var n4Y = o4X * m.b + o4Y * m.d + m.ty; + + r.left = Math.min(n1X, n2X, n3X, n4X); + r.right = Math.max(n1X, n2X, n3X, n4X); + + r.top = Math.min(n1Y, n2Y, n3Y, n4Y); + r.bottom = Math.max(n1Y, n2Y, n3Y, n4Y); + } + } +} diff --git a/job.py b/job.py index 989c991..77c09e8 100644 --- a/job.py +++ b/job.py @@ -3,6 +3,7 @@ import json from validate import * from args import * +import copy asset_src_schema = { "type":"object", @@ -69,19 +70,24 @@ base_path = os.path.join(self.out_dir, self.rel_path) if not os.path.exists(base_path): os.makedirs(base_path) + resource_names = [] for i,r in enumerate(resources): - path = os.path.join(base_path, "%s_%04d.png" % (self.name, i)) + resource_name = "%s_%04d.png" % (self.name, i) if len(resources) > 1 else self.name + ".png" + resource_names.append(resource_name) + path = os.path.join(base_path, resource_name) with open(path, "wb") as f: f.write(base64.b64decode(r)) if len(data) == 1: graphic_and_asset = {} (name, graphic_data) = data.items()[0] - graphic_and_asset = {"data":graphic_data} + graphic_and_asset = {"data":graphic_data, "resources":resource_names} with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps(graphic_and_asset)) else: + write_data = copy.deepcopy(data) + write_data["resources"] = resource_names with open(os.path.join(base_path, self.name + ".asset"), "w") as f: - f.write(pretty_dumps(data)) + f.write(pretty_dumps(write_data)) for name,details in data.iteritems(): with open(os.path.join(base_path, name + ".graphic"), "w") as f: f.write(pretty_dumps({"data":self.name + ".asset"})) diff --git a/old/Checkbox.as b/old/Checkbox.as deleted file mode 100644 index c5aaba2..0000000 --- a/old/Checkbox.as +++ /dev/null @@ -1,42 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - - public class Checkbox extends MovieClip - { - public var Enabled:Boolean = true; - public function Checkbox() - { - checkbox.gotoAndStop(1); - checkbox.addEventListener(MouseEvent.CLICK, Clicked); - } - - protected function Clicked(event) - { - if (!Enabled) return; - Toggle(); - if (OnClick != null) OnClick(OnClickParam); - } - - protected var checked = false; - public function set Checked(value) { checked = value; checkbox.gotoAndStop(checked ? 2 : 1); } - public function get Checked() { return checked; } - - public function set Text(value) { text.text = value; } - - public var OnClickParam; - public var OnClick; - - - public function Toggle() - { - checked = !checked; - checkbox.gotoAndStop(checked ? 2 : 1); - - - } - - } - -} diff --git a/old/GraphicExport-app.xml b/old/GraphicExport-app.xml deleted file mode 100644 index 5144634..0000000 --- a/old/GraphicExport-app.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - GraphicExport - 1.0 - GraphicExport - - GraphicExport - - - GraphicExport.swf - standard - false - true - false - portrait - auto - true - true - true - - - false - false - desktop extendedDesktop diff --git a/old/GraphicExport.exe b/old/GraphicExport.exe deleted file mode 100644 index 56315aa..0000000 --- a/old/GraphicExport.exe +++ /dev/null Binary files differ diff --git a/old/GraphicExport.fla b/old/GraphicExport.fla deleted file mode 100644 index 0b78ed7..0000000 --- a/old/GraphicExport.fla +++ /dev/null Binary files differ diff --git a/old/GraphicExport.swf b/old/GraphicExport.swf deleted file mode 100644 index 542db97..0000000 --- a/old/GraphicExport.swf +++ /dev/null Binary files differ diff --git a/old/NewGraphicDialog.as b/old/NewGraphicDialog.as deleted file mode 100644 index 152011c..0000000 --- a/old/NewGraphicDialog.as +++ /dev/null @@ -1,224 +0,0 @@ -package { - - import flash.display.MovieClip; - import flash.events.MouseEvent; - import flash.events.*; - import flash.filesystem.File; - import flash.net.FileFilter; - import Defs.GraphicDef; - import flash.text.engine.GraphicElement; - - public class NewGraphicDialog extends MovieClip - { - - public function NewGraphicDialog() - { - // constructor code - Init(); - } - - var typeButtons:Array = new Array(); - - public function Init() - { - graphicPath.text = "Path to Graphic Here"; - - this.removeChild(browseButton); - - var newBrowseButton = new UI_GenericBlueButton(); - newBrowseButton.Text = "Browse"; - newBrowseButton.OnClick = BrowseForFile; - newBrowseButton.x = browseButton.x + (newBrowseButton.width / 2); - newBrowseButton.y = browseButton.y + (newBrowseButton.height / 2); - addChild(newBrowseButton); - - var newTestButton = new UI_GenericBlueButton(); - newTestButton.Text = "Export"; - newTestButton.OnClick = TestFile; - newTestButton.x = testButton.x + (newTestButton.width / 2); - newTestButton.y = testButton.y + (newTestButton.height / 2); - addChild(newTestButton); - - this.removeChild(typePlaceholderButton); - - var typeX = typePlaceholderButton.x; - var typeY = typePlaceholderButton.y + (typePlaceholderButton.height / 2); - - - var typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Graphic (1)"; - typeButton.OnClick = function(){ SetType(1); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Skeletal (3)"; - typeButton.OnClick = function(){ SetType(3); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - typeX += typeButton.width + 5; - - typeButton = new UI_GenericBlueButton(); - typeButton.Text = "Scene (6)"; - typeButton.OnClick = function(){ SetType(6); } - typeButton.x = typeX + (typeButton.width / 2); - typeButton.y = typeY; - typeButtons.push(typeButton); - addChild(typeButton); - - animationCheckbox.Checked = true; - //browseButton - //typePlaceholderButton - //usesInput - //usesText.text = "" - } - - var usesInputDefaultText = "Comma Seperated List of Uses Here"; - - public static var fakeID = 9999999; - public function TestFile() - { - fakeID++; - var graphicName = graphicPath.text; - var graphicData = {id:fakeID,graphic:graphicPath.text,v:1,fs:0,p:0,type:selectedType}; - - //"export_params":{"uses":["background"],"available_sizes":["default"],"compress":false}} - - var graphicDef = new GraphicDef(graphicData); - - this.Hide(); - graphicExport.ExportItem(graphicDef); - } - - var selectedType = 1; - public function SetType(type:Number) - { - selectedType = type; - - for(var i = 0; i < typeButtons.length; i++) - { - typeButtons[i].Enabled = true; - } - - animationCheckbox.visible = false; - - switch(type) - { - case 1: { - typeButtons[0].Enabled = false; - animationCheckbox.visible = true; - break; - } - case 3: typeButtons[1].Enabled = false; break; - case 6: typeButtons[2].Enabled = false; break; - } - } - - var graphicExport:GraphicExport; - public function Show(parentClip) - { - this.graphicExport = parentClip; - - parentClip.addChild(this); - - SetType(selectedType); - - var graphicList = GameData.Instance().GraphicDefines; - - var usesString:String = ""; - var uniqueUseTypes:Array = new Array(); - for (var i = 0; i < graphicList.length; i++) - { - var graphicDef:GraphicDef = graphicList[i]; - var uses = graphicDef.ExportParams['uses']; - for (var usage in uses) - { - if (uniqueUseTypes[uses[usage]] == null) - { - uniqueUseTypes[uses[usage]] = uses[usage]; - usesString += uses[usage] + ", "; - } - } - } - - graphicPath.text = ""; - - } - - public function CloseClicked(event) - { - Hide(); - } - - public function Hide() - { - if (this.parent != null) this.parent.removeChild(this); - } - - public function BrowseForFile() - { - var file:File = new File(); - var swfTypeFilter:FileFilter = new FileFilter("SWF Files","*.swf"); - file.addEventListener(Event.SELECT, openFile); - file.browse([swfTypeFilter]); - } - - private function openFile(event:Event):void - { - _strace(event.target.nativePath); - var path:String = event.target.nativePath; - var pathParts:Array = path.split("Graphics\\"); - if (pathParts.length == 2) - { - var fileRemainder:String = pathParts[1]; - var withoutExtension:String = fileRemainder.split(".")[0]; - var pattern:RegExp = /\\/g; - withoutExtension = withoutExtension.replace(pattern, "/"); - _strace(withoutExtension); - graphicPath.text = withoutExtension; - - if (withoutExtension.indexOf("Backgrounds") > -1) - { - SetType(6); - } - - if (withoutExtension.indexOf("Monsters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Characters") > -1) - { - SetType(3); - } - - if (withoutExtension.indexOf("Portraits") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Quest") > -1) - { - SetType(1); - } - - if (withoutExtension.indexOf("Equipment") > -1) - { - SetType(1); - } - - - } - } - - - } - -} diff --git a/old/PNGExportHelper.as b/old/PNGExportHelper.as deleted file mode 100644 index f8c4c9d..0000000 --- a/old/PNGExportHelper.as +++ /dev/null @@ -1,253 +0,0 @@ -package -{ - import flash.display.*; - import com.adobe.images.*; - import flash.utils.*; - import flash.net.*; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import flash.geom.Point; - - public class PNGExportHelper - { - public static var UseExpandedBitmaps = false; - public static var AlphaThreshold = 5; - - private static function ExpandBitmapBorders(bd:BitmapData, bgColor = 0x0, passes = 1):BitmapData - { - /* - var thresh:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - thresh.threshold(bd, bd.rect, new Point(), "<", (20 << 24), bgColor, 0xFF000000, true); - */ - var sampled:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - bd.lock(); - sampled.lock(); - - for (var y = 0; y < bd.height; y++) - { - for (var x = 0; x < bd.width; x++) - { - var oldVal:uint = bd.getPixel32(x, y); - var a:uint = (oldVal & 0xFF000000) >>> 24; - var rgb:uint = (oldVal & 0xFFFFFF); - if (a > AlphaThreshold) - { - sampled.setPixel32(x, y, (0xFF << 24) | rgb); - } - else - { - sampled.setPixel32(x, y, bgColor); - } - } - } - sampled.unlock(); - bd.unlock(); - - return ExpandBitmapBordersInternal(sampled, bgColor, passes); - } - - private static function ExpandBitmapBordersInternal(bd:BitmapData, bgColor, passes):BitmapData - { - var output:BitmapData = new BitmapData(bd.width, bd.height, true, bgColor); - - var scale = 16; - var scaled:BitmapData = new BitmapData(bd.width/scale, bd.height/scale, true, bgColor); - var mat:Matrix = new Matrix(); - mat.scale(1/scale, 1/scale); - scaled.draw(bd, mat, null, null, null, true); - - output.lock(); - - var colors:Array = new Array(); - var weights:Array = new Array(); - - for (var oy = 0; oy < scaled.height; oy++) - { - - for (var ox = 0; ox < scaled.width; ox++) - { - - var scaledVal:uint = scaled.getPixel32(ox, oy); - var scaleda:uint = (scaledVal & 0xFF000000) >>> 24; - if (scaleda == 0 || scaleda == 255) - { - output.copyPixels(bd, new Rectangle(ox * scale, oy * scale, scale, scale), new Point(ox * scale, oy * scale)); - continue; - } else { - //_strace(scaleda+""); - } - - - for (var y = oy * scale; y < oy * scale + scale; y++) - { - for (var x = ox * scale; x < ox * scale + scale; x++) - { - var oldVal:uint = bd.getPixel32(x, y); - var a:uint = (oldVal & 0xFF000000) >>> 24; - var rgb:uint = (oldVal & 0xFFFFFF); - - if (a == 0 && rgb == bgColor) - { - colors.length = 0; - weights.length = 0; - - for (var y1 = y - 2; y1 <= y + 2; y1++) - { - for (var x1 = x - 2; x1 <= x + 2; x1++) - { - var dist = Math.abs(x1 - x) + Math.abs(y1 - y); - if (dist >= 3) continue; - - if (x1 >= 0 && x1 < bd.width && y1 >= 0 && y1 < bd.height) - { - colors.push(bd.getPixel(x1, y1)); - weights.push(1 - dist * 0.2); - } - } - } - - var newVal = AveragePixels(colors, weights, bgColor); - if (newVal == null) - { - newVal = oldVal; - } - else - { - var newR:uint = (newVal & 0xFF0000) >> 16; - var newG:uint = (newVal & 0xFF00) >> 8; - var newB:uint = (newVal & 0xFF); - - if (newVal != 0 && colors.length >= 4) - { - var bp = true; - } - - var sorted = colors.sort(function(a, b) - { - var aR:uint = (a & 0xFF0000) >> 16; - var aG:uint = (a & 0xFF00) >> 8; - var aB:uint = (a & 0xFF); - - var bR:uint = (b & 0xFF0000) >> 16; - var bG:uint = (b & 0xFF00) >> 8; - var bB:uint = (b & 0xFF); - - var diffA = Math.abs(aR - newR) + Math.abs(aG - newG) + Math.abs(aB - newB); - var diffB = Math.abs(bR - newR) + Math.abs(bG - newG) + Math.abs(bB - newB); - - return diffA - diffB; - - }, Array.RETURNINDEXEDARRAY | Array.DESCENDING); - - var toRemove = Math.min(2, colors.length - 4); - var removed = 0; - for (var i = 0; i < colors.length; i++) - { - var index = sorted.indexOf(i + removed); - if (index < toRemove) - { - colors.splice(i, 1); - weights.splice(i, 1); - removed++; - i--; - if (removed == toRemove) break; - } - } - - var fixOutliersVal = AveragePixels(colors, weights, bgColor); - if (fixOutliersVal == null) newVal = (0xFF << 24) | newVal; - - newVal = (0xFF << 24) | fixOutliersVal; - } - - output.setPixel32(x, y, newVal); - } - else - { - output.setPixel32(x, y, oldVal); - } - } - } - }//end outer scaled x - }//End outer scaled y - - bd.unlock(); - output.unlock(); - - passes--; - if (passes > 0) - { - return ExpandBitmapBordersInternal(output, bgColor, passes); - } - else - { - return output; - } - } - - private static function AveragePixels(colors:Array, weights:Array, bgColor:uint):uint - { - var rTotal = 0; - var gTotal = 0; - var bTotal = 0; - - var wTotal = 0; - - for (var i = 0; i < colors.length; i++) - { - var color:uint = colors[i]; - var a:uint = (color & 0xFF000000) >>> 24; - var rgb:uint = (color & 0xFFFFFF); - - if (a == 0 && rgb == bgColor) - { - colors.splice(i, 1); - weights.splice(i, 1); - i--; - continue; - } - - var r:uint = (rgb & 0xFF0000) >>> 16; - var g:uint = (rgb & 0xFF00) >>> 8; - var b:uint = (rgb & 0xFF); - var w = weights[i]; - - rTotal += w * r; - gTotal += w * g; - bTotal += w * b; - - wTotal += w; - } - - if (wTotal == 0) - { - return null; - } - - rTotal /= wTotal; - gTotal /= wTotal; - bTotal /= wTotal; - - var rFinal = Math.max(0, Math.min(255, Math.round(rTotal))); - var gFinal = Math.max(0, Math.min(255, Math.round(gTotal))); - var bFinal = Math.max(0, Math.min(255, Math.round(bTotal))); - - return (uint(rFinal) << 16) | (uint(gFinal) << 8) | (uint(bFinal)); - } - - - - public static function GetExportPNG(bd:BitmapData):ByteArray - { - if (!UseExpandedBitmaps) return PNGEncoder.encode(bd); - - var expanded:BitmapData = ExpandBitmapBorders(bd, 0x0, 2); - - //var fr:FileReference = new FileReference(); - //fr.save(PNGEncoder.encode(expanded), "output.png"); - - return PNGEncoderWithAlpha.encode(expanded, bd); - } - - } -} \ No newline at end of file diff --git a/old/PreviewHolder.as b/old/PreviewHolder.as deleted file mode 100644 index 587bf68..0000000 --- a/old/PreviewHolder.as +++ /dev/null @@ -1,57 +0,0 @@ -package { - import flash.display.MovieClip; - - public class PreviewHolder extends MovieClip - { - - var startingWidth = 1024; - var startingHeight = 1024; - - public function PreviewHolder() - { - startingWidth = this.width; - startingHeight = this.height; - } - - var clips:Array = new Array(); - public function AddClip(clip) - { - clips.push(clip); - this.addChild(clip); - ArrangeClips(); - } - - public function ArrangeClips() - { - var numCols = Math.ceil(Math.sqrt(clips.length)); - var maxY = 0; - var maxX = 0; - var clipIndex = 0; - for (var row = 0; row < numCols; row++) - { - var clipX = 0; - var clipY = maxY; - for (var col = 0; col < numCols; col++) - { - if (clipIndex == clips.length) break; - clips[clipIndex].x = clipX; - clips[clipIndex].y = clipY; - clipX += clips[clipIndex].width; - var clipBottom = clips[clipIndex].y + clips[clipIndex].height; - if (clipBottom > maxY) maxY = clipBottom; - - var clipRight = clips[clipIndex].x + clips[clipIndex].width; - if (clipRight > maxX) maxX = clipRight; - clipIndex++; - } - } - - var scale = Math.min(startingWidth / maxX, startingHeight / maxY); - if (scale > 1) scale = 1; - - this.scaleX = this.scaleY = scale; - } - - } - -} diff --git a/old/Utils.as b/old/Utils.as deleted file mode 100755 index 02b4f12..0000000 --- a/old/Utils.as +++ /dev/null @@ -1,1202 +0,0 @@ -package old -{ - /* This class has functions similar to the Utils.as in the /flash/Dialogs folder. However, some of - * those functions are different here than in /flash/Dialogs/Utils.as for... reasons? flash folder reasons! - */ - import flash.utils.*; - import flash.net.*; - import flash.display.*; - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFieldType; - import flash.text.TextFieldAutoSize; - import flash.text.TextFormatAlign; - import flash.geom.Point; - import flash.geom.Matrix; - import flash.geom.Rectangle; - import flash.geom.ColorTransform; - import fl.motion.Color; - import fl.transitions.Tween; - import fl.transitions.easing.*; - import fl.transitions.TweenEvent; - import flash.net.navigateToURL; - import flash.external.ExternalInterface; - import flash.system.Capabilities; - import flash.filters.*; - import flash.filters.ColorMatrixFilter; - import com.adobe.images.JPGEncoder; - import flash.globalization.DateTimeFormatter; - - import djarts.utils.Base64; - import djarts.utils.PNGEnc; - import User.UserOptions; - - public class Utils - { - //["K","M","B","T","q", "Q", "s", "S","O","N","d","U","D","!","@","#","$","%","^","&","*"] - static var symbols = ["K","M","B","t","q", "Q", "s", "S","o","n","d","U","D","T","Qt","Qd","Sd","St","O","N","v","c"]; - static var divisors = []; - - public static function FormatBigNumber(number:*, round:Boolean=false):String - { - if (number < 0) return '-' + FormatBigNumber(Math.abs(number), round); - - var isWholeNumber = (Math.floor(number) == number); - round = round || isWholeNumber; - - if (number < 1000) - { - if (round) - { - return Math.round(number).toString(); - } - else - { - var decimalPlaces = (number >= 100) ? 1 : 2; // Below 100, show two decimal places. Above, only one. - var roundMult = Math.pow(10, decimalPlaces); - var rounded = Math.round(number); - var bigRounded = Math.round(number * roundMult); - var roundedDifferenceProportion = Math.abs(bigRounded / roundMult - rounded) / rounded; - - if (roundedDifferenceProportion < 0.001) - { - // Not a whole number, but the decimal places aren't worth showing - // Below also handles this, but is slower - return rounded.toString(); - } - else - { - var str:String = bigRounded.toString(); - str = str.substr(0, str.length - decimalPlaces) + "." + str.substr(str.length - decimalPlaces); - - while (str.charAt(str.length - 1) == "0") str = str.substr(0, str.length - 1); //should only ever happen once - if (str.charAt(str.length - 1) == ".") str = str.substr(0, str.length - 1); //probably won't happen at all - - return str; - } - } - } - - // Determine which symbol to use - var power = Math.floor(Math.log(number) / Math.log(1000)); - var index = Math.min(power-1, symbols.length-1); - var amount = number / Math.pow(1000, index+1); - var symbol = (index >= 0 && index < symbols.length) ? symbols[index] : ""; - - // If it's too big for a symbol (or if we just WANT to) - if (amount >= 1000 || UserOptions.ForceScientific) - { - // scientific notation - var power = Math.floor(Math.log(number) / Math.log(10)); - var num = number / Math.pow(10, power); - if (num == 10) { - num = 1; - power += 1; - } - var numString = "" + num; - numString = numString.substr(0, Math.min(4, numString.length)); - return numString + "e" + power; - - } - else - { - // Format with the symbol - // determine number of whole digits (will dictate how many decimals we show) - var whole = Math.floor(amount); - var amount_str:String = String(whole); - - var decimalDivider = 100/Math.pow(10,amount_str.length-1); - - //round to nearest decimal place - amount = int(amount*decimalDivider)/decimalDivider; - - var amountString:String = amount.toString(); - - var noDecimal:String = amountString.replace(".",""); - if (noDecimal.length == 2) - { - if (amountString.indexOf(".") != -1) amountString += "0"; - else amountString += ".0"; - } - else if (noDecimal.length == 1) amountString += ".00"; - - return amountString+symbol; // concat symbol - } - } - - private static var BigNumberRegex = new RegExp(/(\d*),?(\d*)(.*)/); - // Note-DG: This is mostly just used for definitions in the database, that don't require precision. - // This way we can define values in the database as 100B instead of 100000000000. - public static function ParseBigNumberString(number:String):Number - { - var regexArray:Array = BigNumberRegex.exec(number); - var magnitude = symbols.indexOf(regexArray[3]); - var thousands:Number; - if (regexArray[1]) { - thousands = regexArray[1]; - if (regexArray[2]) { // if numbers are split by comma, multiply by 1000 - thousands *= 1000; - } - } else { - thousands = 0; - } - var hundreds:Number = regexArray[2] ? regexArray[2] : 0; - - return (thousands + hundreds) * Math.pow(1000, magnitude + 1); - } - - public static function ParseNumberRange(range:String):Array - { - var split:Array = range.split(','); - return [Number(split[0]), Number(split[1])]; - } - - public static function DesaturateFilter() - { - var desatMatrix:Array = []; - var cmFilter; - - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // red - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // green - desatMatrix = desatMatrix.concat([0.309, 0.609, 0.082, 0, 0]); // blue - desatMatrix = desatMatrix.concat([0, 0, 0, 1, 0]); // alpha - cmFilter = new ColorMatrixFilter(desatMatrix); - - return cmFilter; - } - - public static function GetUserAgent():String - { - try - { - var userAgent = ExternalInterface.call("window.navigator.userAgent.toString"); - var browser:String = "[Unknown Browser]"; - - if (userAgent.indexOf("Safari") != -1) - { - browser = "Safari"; - } - if (userAgent.indexOf("Firefox") != -1) - { - browser = "Firefox"; - } - if (userAgent.indexOf("Chrome") != -1) - { - browser = "Chrome"; - } - if (userAgent.indexOf("MSIE") != -1) - { - browser = "Internet Explorer"; - } - if (userAgent.indexOf("Opera") != -1) - { - browser = "Opera"; - } - } - catch (e:Error) - { - //could not access ExternalInterface in containing page - return "[No ExternalInterface]"; - } - - return browser; - } - - public static function GetScreenshot(stage:Stage):String { - var scale:Number = 0.25; - var result:String = null; - var blurFilter:BlurFilter = new BlurFilter(3, 3, BitmapFilterQuality.HIGH); - - var bData:BitmapData = new BitmapData(stage.stageWidth * scale, - stage.stageHeight * scale, false, 0x348400); - var matrix:Matrix = new Matrix(); - matrix.scale(scale, scale); - - bData.draw(stage, matrix); - bData.applyFilter(bData, bData.rect, new Point(0, 0), blurFilter); - - - var imgBytes:ByteArray = new JPGEncoder(80).encode(bData); - //var imgBytes:ByteArray = PNGEnc.encode(bData); - if (imgBytes) { - var screenshotBase64:String = Base64.encode(imgBytes); - if (screenshotBase64) { - result = screenshotBase64; - } - } - - return result; - } - - public static function RecursivelyStop(clip, frame = null) - { - if (clip is MovieClip) - { - if (frame == null) - { - clip.stop(); - } else { - clip.gotoAndStop(frame); - } - } - if (clip is DisplayObjectContainer) - { - for (var i = 0; i < clip.numChildren; i++) - { - RecursivelyStop(clip.getChildAt(i)); - } - } - } - - public static function PlayerVersion() - { - - // Get the player's version by using the getVersion() global function. - var versionNumber:String = Capabilities.version; - - // The version number is a list of items divided by "," - var versionArray:Array = versionNumber.split(","); - var length:Number = versionArray.length; - //for(var i:Number = 0; i < length; i++) _strace("versionArray["+i+"]: "+versionArray[i]); - - // The main version contains the OS type too so we split it in two - // and we'll have the OS type and the major version number separately. - var platformAndVersion:Array = versionArray[0].split(" "); - //for(var j:Number = 0; j < 2; j++) _strace("platformAndVersion["+j+"]: "+platformAndVersion[j]); - //_strace("-----"); - - var majorVersion:Number = parseInt(platformAndVersion[1]); - var minorVersion:Number = parseInt(versionArray[1]); - var buildNumber:Number = parseInt(versionArray[2]); - - return Number(majorVersion+"."+minorVersion); - } - - - public static function OpenLocalURLTop(url) - { - navigateToURL(new URLRequest(GameSettings.Approot+url), "_top" ); - } - - public static function OpenLocalURL(url) - { - navigateToURL(new URLRequest(GameSettings.Approot+url), "_blank" ); - } - - public static function OpenURL(url, window = "_blank") - { - navigateToURL(new URLRequest(url), window); - } - - public static var ExitFullScreenCallback; - - public static function WallPublish(title:String, desc1:String, desc2:String, image:String, url = null, action = null) - { - if (Utils.ExitFullScreenCallback) Utils.ExitFullScreenCallback(); - //_strace(title + "\n" + desc1 + "\n" + desc2 + "\n" + image + "\n"); - ExternalInterface.call("askToPublish", title, url, desc1, desc2, image, action); - - //if (Settings.Platform == Settings.HI5) { - //DialogManager.Instance().ShowMessageBox("The message was posted to your wall!", "", "OK", null); - //} - } - - public static function SendToRecipients(recipients:Array, description, data) - { - if (!GameSettings.IsFacebook) return; - - if (Utils.ExitFullScreenCallback) Utils.ExitFullScreenCallback(); - try { - ExternalInterface.call("sendToRecipients", recipients, description ,data); - } - catch (e) - { - _strace(e.message); - } - } - - - public static function GetFriendData() - { - try { - return ExternalInterface.call("pollInviteData"); - } - catch (e) - { - _strace(e.message); - } - } - - - public static function singleBounceEase(t:Number, b:Number, c:Number, d:Number):Number - { - t = t / d; - if (t < 0.7) { - t *= 1.0 / 0.65; - return c * (t * t) + b; - } - return c * (t * t) + b; - } - - public static function Finish(e:TweenEvent) - { - //_strace("done " + e.currentTarget.obj.x + " " + e.currentTarget.obj.y + " " + e.currentTarget.obj.scaleX + " " + e.currentTarget.obj.scaleY); - e.currentTarget.removeEventListener(TweenEvent.MOTION_FINISH, Finish); - } - public static function Popup(mc, startScale = 0.8, finishCallback = null) - { - var rect:Rectangle = mc.getRect(mc); - var targetX = mc.x; - var targetY = mc.y; - var centerX = mc.x + rect.left + mc.width / 2.0; - var centerY = mc.y + rect.top + mc.height / 2.0; - var startX = centerX - (rect.left + mc.width / 2.0) * startScale; - var startY = centerY - (rect.top + mc.height / 2.0) * startScale; - var tweenSX = new Tween(mc, "scaleX", singleBounceEase, startScale, 1.0, 4, false); - if (finishCallback) tweenSX.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenSY = new Tween(mc, "scaleY", singleBounceEase, startScale, 1.0, 4, false); - if (finishCallback) tweenSY.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenX = new Tween(mc, "x", singleBounceEase, startX, targetX, 4, false); - if (finishCallback) tweenX.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - var tweenY = new Tween(mc, "y", singleBounceEase, startY, targetY, 4, false); - if (finishCallback) tweenY.addEventListener(TweenEvent.MOTION_FINISH, finishCallback); - return [tweenSX, tweenSY, tweenX, tweenY]; - } - public static function StringSplit(s:String, delim:String, max:int = -1):Array - { - var ret:Array = s.split(delim); - if (max != -1) { - var more:String = ret.slice(max - 1).join(delim); - ret.splice(max - 1); - ret[max - 1] = more; - } - return ret; - } - - public static function StringStartsWith(str:String, substr:String):Boolean - { - if (substr.length > str.length) return false; - return (str.substr(0, substr.length) == substr); - } - - public static function StringEndsWith(str:String, substr:String):Boolean - { - if (substr.length > str.length) return false; - return (str.substr(str.length - substr.length, substr.length) == substr); - } - - public static function StringContains(str:String, substr:String):Boolean - { - return (str.indexOf(substr) !== -1); - } - - private static var vowelsAndH = { - "a":true, "A":true, - "e":true, "E":true, - "i":true, "I":true, - "o":true, "O":true, - "u":true, "U":true, - "h":true, "H":true - } - public static function StringStartsWithVowelOrH(s:String):Boolean - { - if (vowelsAndH[s.charAt(0)]) return true; - return false; - } - - public static function CopyObject(obj, except = null) - { - var i; - if (except == null) except = []; - if (obj is Array) { - var obj2 = []; - for (i = 0; i < obj.length; i++) { - obj2.push(Utils.CopyObject(obj[i])); - } - return obj2; - } - var ret:Object = {}; - for (i in obj) - { - if (except.indexOf(i) == -1) { - ret[i] = obj[i]; - } - } - - return ret; - } - public static function CopyToObject(objFrom, objTo, except = null) - { - if (except == null) except = []; - for (var i in objFrom) - { - if (except.indexOf(i) == -1) { - objTo[i] = objFrom[i]; - } - } - } - public static function CopyToObjectOnly(objFrom, objTo, only) - { - if (only == null) return; - for (var i in only) - { - if (objFrom.hasOwnProperty(only[i])) - { - objTo[only[i]] = objFrom[only[i]]; - } - } - } - - public static function ColorizeRGB(clip:MovieClip, r:int,g:int,b:int) - { - var cTransform = clip.transform.colorTransform; - cTransform.redOffset = r; - cTransform.greenOffset = g; - cTransform.blueOffset = b; - clip.transform.colorTransform = cTransform; - } - - public static function hex2rgb (hex):Object - { - var red = hex>>16; - var greenBlue = hex-(red<<16) - var green = greenBlue>>8; - var blue = greenBlue - (green << 8); - return({r:red, g:green, b:blue}); - } - - public static function RGBtoHEX(r, g, b) { - return r << 16 | g << 8 | b; - } - - /** - * NOTE: An alpha of 1 will make the object a solid color (good for silhouettes) - */ - public static function TintDisplayObject(obj:DisplayObject, color:uint = 0xffffff, alpha:Number = 1.0) - { - var cTint:Color = new Color(); - cTint.setTint(color, alpha); - obj.transform.colorTransform = cTint; - } - - // given an origin (ox, oy) and a look at point (tx, ty), - // and a clip with the given number of rotation states, which - // rotation should we pick? - public static function Rotation(ox, oy, tx, ty, rotations) - { - var delta:Point = new Point(tx - ox, ty - oy); - if (Point.distance(delta, new Point(0.0, 0.0)) < 0.00001) { - delta.y = -1.0; - } - var d = ( - (-Math.floor( - /* calculate the rotation and scale it */ - Math.atan2(delta.y, delta.x) / (Math.PI * 2.0) * rotations - + 0.5 // add 0.5 and take the floor (round to closest int) - ) - + rotations) // atan2 returns in the range -pi to pi, measured ccw from +x, - // we negate it and add rotations again to get it in the range - // [0, rotations] - % rotations) + 1; // add 1 to reference frames - return d; - } - /* performs multiple operations asynchronously, but wait for them all to finish: - * instead of calling a bunch of functions and passing callbacks, pass those callbacks to WaitForFunctions - * and use ret.callbacks[0], ret.callbacks[1], etc... as the callbacks - * this will wait until every command is complete and call all the callbacks at once. - * - * For instance, to load multiple graphics packs asynchronously and wait for them all to finish, - * call var ret = WaitForFunctions([DoneLoading, null, null, null]); to generate - * ret.callbacks[0]..ret.callbacks[3], and pass these to 4 calls to LoadExternalGraphics. - * When these 4 calls complete, the provided 4 functions will be called with the arguments returned - * from the callbacks (in this case, only DoneLoading will be called since the - * other callbacks are null). - */ - public static function WaitForFunctions(...funcs):Object - { - var ret:Object = {}; - // has a callback been hit? - ret.hit = new Array(funcs.length); - // what were the original arguments the callback was called with - ret.args = new Array(funcs.length); - // a list of the artifical callbacks we are providing - ret.callbacks = new Array(funcs.length); - // the real callbacks - ret.funcs = funcs; - ret.done = false; - - ret.immediate = []; - - for (var i = 0; i < funcs.length; i++) { - // we have to setup this temp callback in another function, because the anon function's - // activation object will contain the current scope, meaning that the variable - // i will be updated in each function; if we do it in a seperate function each - // activation object will reference a different i - ret.callbacks[i] = Utils.SetupFunction(ret, i); - } - return ret; - } - - /** - * Returns the standard money format for an integer amount - */ - public static function FormatCurrency(amount:int, symbol:String = "$"):String - { - var afterDecimal:String = (amount % 100).toString(); - while (afterDecimal.length < 2) afterDecimal = "0" + afterDecimal; //mmmm string concatenation - - var beforeDecimal:String; - if (amount > 100) - { - beforeDecimal = Math.floor(amount/100).toString(); - } - else - { - beforeDecimal = "0"; - } - - return symbol + beforeDecimal + "." + afterDecimal; - } - - public static function FormatNumber(amount){ - var whole = Math.floor(amount); - // convert the number to a string - var amount_str:String = String(whole); - var total_str:String = String(amount); - - var number_array:Array = []; - var start:Number; - var end:Number = amount_str.length; - while (end > 0) { - start = Math.max(end - 3, 0); - number_array.unshift(amount_str.slice(start, end)); - end = start; - } - - var point = total_str.indexOf("."); - - var ret = number_array.join(","); - if (point != -1 && point < total_str.length) - { - ret += total_str.substr(point); - } - - return ret; - } - - protected static function SetupFunction(ret, i):Function - { - var a:Function = - function(...rest) { - if (ret.immediate[i]) ret.immediate[i].apply(null, rest); - ret.hit[i] = true; - ret.args[i] = rest; - var ok:Boolean = true; - var j; - for (j = 0; j < ret.hit.length; j++) { - if (!ret.hit[j]) { ok = false; break; } - } - if (ok && !ret.done) { - ret.done = true; - for (j = 0; j < ret.funcs.length; j++) { - if (ret.funcs[j] != null) ret.funcs[j].apply(null, ret.args[j]); - } - } - }; - return a; - } - - // useful for the paned dialogs to show a certain pane/button - public static function OnlyVisible(obj, set:Array, index:int) - { - for (var i in set) { - if (i != index) { - obj[set[i]].visible = false; - } else { - obj[set[i]].visible = true; - } - } - } - public static function AllVisible(obj, set:Array) - { - for (var i in set) { - obj[set[i]].visible = true; - } - } - // set one of a list of tabs to be enabled - public static function OnlyToggled(obj, set:Array, index:int) - { - for (var i in set) { - if (i != index) { - obj[set[i]].SetToggled(false); - } else { - obj[set[i]].SetToggled(true); - } - } - } - // get the frame number of a label in the timeline - public static function GetLabelFrame(mc, name:String):int - { - for (var l in mc.currentLabels) { - if (mc.currentLabels[l].name == name) return mc.currentLabels[l].frame; - } - return 1; - } - // generate a quick text field of a certain color/style - public static function BasicTextField(color:uint, - size:int, - font:String, - text:String, - additional:Object = null, - align = "left"):TextField - { - var t:TextField = new TextField(); - var f:TextFormat = new TextFormat(); - f.align = align; - if (additional != null) for (var a in additional) f[a] = additional[a]; - f.font = font; - f.color = color; - f.size = size; - t.type = TextFieldType.DYNAMIC; - t.defaultTextFormat = f; - t.text = text; - t.selectable = false; - t.autoSize = TextFieldAutoSize.LEFT; - return t; - } - public static function var_dump(_obj, name = "Dump") - { - _strace(name + " " + (_obj) + " {"); - flash.utils.describeType(_obj); - var varList:XMLList = flash.utils.describeType(_obj)..variable; - - for(var i:int; i < varList.length(); i++) - { - //Show the name and the value - _strace(" " + varList[i].@name+' = '+ _obj[varList[i].@name]); - } - _strace("}"); - } - - public static function SetChildFrames(parentClip, frame, exclude = null) - { - if (parentClip is MovieClip && parentClip.name != exclude) - { - parentClip.gotoAndStop(frame); - for (var i = 0; i < parentClip.numChildren; i++) - { - Utils.SetChildFrames(parentClip.getChildAt(i), frame, exclude); - } - } - } - - public static function SetChildFramesNoParent(parentClip, frame, exclude = null) - { - if (parentClip is MovieClip && parentClip.name != exclude) - { - for (var i = 0; i < parentClip.numChildren; i++) - { - Utils.SetChildFrames(parentClip.getChildAt(i), frame, exclude); - } - } - } - - //modifies the array passed as parameter, following the MO of the built in Array.sort() - public static function insertionSort(array:Array, compareFunction:Function):void - { - for(var i:int=1; i < array.length; i++) - { - var value:Object = array[i]; - var k:int=i-1; - while( k >= 0 && compareFunction(array[k], value) == -1) - { - array[k+1]=array[k]; - k--; - } - array[k+1]=value; - } - } - - - public static function Screenshot(sourceClip, receiverURL, filename) - { - - var jpgSource:BitmapData; - - if (sourceClip is Stage) - { - jpgSource = new BitmapData (sourceClip.stageWidth, sourceClip.stageHeight); - } else { - jpgSource = new BitmapData (sourceClip.width, sourceClip.height); - } - - jpgSource.draw(sourceClip); - - var jpgEncoder:JPGEncoder = new JPGEncoder(85); - var jpgStream:ByteArray = jpgEncoder.encode(jpgSource); - - var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream"); - var jpgURLRequest:URLRequest = new URLRequest(receiverURL+"?name="+filename); - jpgURLRequest.requestHeaders.push(header); - jpgURLRequest.method = URLRequestMethod.POST; - jpgURLRequest.data = jpgStream; - navigateToURL(jpgURLRequest, "_blank"); - - } - - - public static function SetColors(clip, color) - { - var colorTransform:ColorTransform; - - if (clip == null || color == null) return; - - if (clip.hasOwnProperty("outline") && clip.outline != null) - { - colorTransform = clip.outline.transform.colorTransform; - colorTransform.color = color.Outline; - clip.outline.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryOutline") && clip.secondaryOutline != null) - { - colorTransform = clip.secondaryOutline.transform.colorTransform; - colorTransform.color = color.LightOutline; - clip.secondaryOutline.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("color") && clip.color != null) - { - colorTransform = clip.color.transform.colorTransform; - colorTransform.color = color.Primary; - clip.color.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryColor") && clip.secondaryColor != null) - { - colorTransform = clip.secondaryColor.transform.colorTransform; - colorTransform.color = color.Secondary; - clip.secondaryColor.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("shadow") && clip.shadow != null) - { - colorTransform = clip.shadow.transform.colorTransform; - colorTransform.color = color.Shadow; - clip.shadow.transform.colorTransform = colorTransform; - } - - if (clip.hasOwnProperty("secondaryShadow") && clip.secondaryShadow != null) - { - colorTransform = clip.secondaryShadow.transform.colorTransform; - colorTransform.color = color.SecondaryShadow; - clip.secondaryShadow.transform.colorTransform = colorTransform; - } - } - /* returns a rect with the x, and y pos to center and the scaleX and scaleY as width and height */ - public static function GetUniformScaleRect(clip:MovieClip, maxWidth, maxHeight) - { - var rect:Rectangle = new Rectangle(0,0,0,0); - - var widthScale = Math.min(maxWidth / clip.width, 999); - var heightScale = Math.min(maxHeight / clip.height, 999); - - var scale = 1; - if (widthScale > heightScale) - { - scale = heightScale; - } else { - scale = widthScale; - } - - rect.width = clip.width * scale; - rect.height = clip.height * scale; - - var pb = clip.getBounds(clip); - var xadjust = -pb.left * scale; - var yadjust = -pb.top * scale; - - rect.x = xadjust + (maxWidth - rect.width) / 2; - rect.y = yadjust + (maxHeight - rect.height) / 2; - - rect.width = scale; - rect.height = scale; - - return rect; - } - - public static function Dec2Hex(d) - { - var chars:String = "0123456789ABCDEF"; - var str:String = ""; - while (d > 0 || str.length < 2) - { - var digit = d % 16; - d = (d - digit) / 16; - str = chars.charAt(digit) + str; - } - return str; - } - - public static function Hex2Dec(h:String) - { - var chars:String = "0123456789ABCDEF"; - var val = 1; - var res = 0; - for (var i = h.length - 1; i >= 0; i--) - { - res += chars.indexOf(h.substr(i, 1)) * val; - val *= 16; - } - return res; - } - - public static function ShallowCopyArray(array:Array) - { - if (!array) return null; - - var newArray:Array = []; - for (var i:int = 0; i < array.length; i++) - { - newArray.push(array[i]); - } - return newArray; - } - - /* Note: Will fail if any items in either array have reference type semantics (unless they point to the same object) - * (as opposed to value type semantics) - */ - public static function areEqual(a:Array,b:Array):Boolean { - if(a.length != b.length) { - return false; - } - var len:int = a.length; - for(var i:int = 0; i < len; i++) { - if(a[i] !== b[i]) { - return false; - } - } - return true; - } - - /* Note: Will fail if any items in either array have reference type semantics - * (as opposed to value type semantics) - */ - public static function objectsAreEqual(a:Object,b:Object):Boolean { - - for (var i in a) - { - if (!b.hasOwnProperty(i) || a[i] != b[i]) return false; - } - - return true; - } - - public static function DeepCopyClone (source : Object) : * - { - var array : ByteArray = new ByteArray (); - - array.writeObject (source); - array.position = 0; - - return array.readObject (); - } - - // {a:1, b:2} => [1,2] - public static function ObjectValues (obj:Object):Array { - var array = []; - for (var key in obj) array.push(obj[key]); - return array; - } - - // {a:1, b:2} => ["a","b"] - public static function ObjectKeys (obj:Object):Array { - var array = []; - for (var key in obj) array.push(key); - return array; - } - - // normal random variate generator; mean m, standard deviation s - public static function BoxMullerRandomNormal(m:Number, s:Number) : Number - { - var x1, x2, w, y1:Number; - var y2:Number; - var use_last:Boolean = false; - - if (use_last == true) /* use value from previous call */ - { - y1 = y2; - use_last = false; - } - else - { - do { - x1 = 2.0 * Math.random() - 1.0; - x2 = 2.0 * Math.random() - 1.0; - w = x1 * x1 + x2 * x2; - } while ( w >= 1.0 ); - - w = Math.sqrt( (-2.0 * Math.log( w ) ) / w ); - y1 = x1 * w; - y2 = x2 * w; - use_last = true; - } - - return( m + y1 * s ); - } - - public static function SanitizeNumber(n) - { - if (n is Number) - { - if (n == Number.NEGATIVE_INFINITY || n == Number.POSITIVE_INFINITY || n == Number.NaN) return 0; - } - return n; - } - - public static function IsNumberInvalid(n) - { - if (n is Number) - { - if (n == Number.NEGATIVE_INFINITY || n == Number.POSITIVE_INFINITY || n == Number.NaN) return true; - } - return false; - } - - public static function LimitNumberToMax(n) - { - if (n == Number.POSITIVE_INFINITY) return Number.MAX_VALUE; - return n; - } - - /* - value= Math.round(20/7); - value= int((20/7)*10)/10; - value= int((20/7)*100)/100; - value= int((20/7)*1000)/1000; - value= int((20/7)*10000)/10000; - */ - public static function RoundToDecimalPlaces(number:Number, places:int) - { - return Math.round((number)*Math.pow(10,places))/Math.pow(10,places); - } - - public static function GetShuffledArray(a:Array) : Array - { - var r:Array = a.concat(); - r.sort(randomSort); - return r; - } - - ///Convenience function since I keep forgetting the name of randomSort (hint: it's randomSort) - public static function ShuffleArray(a:Array) - { - a.sort(randomSort); - } - - public static function PickRandom(a:Array) - { - return a[Math.floor(Math.random() * a.length)]; - } - - /** - * Returns n elements of array a, up to a maximum of a's length. - * If forceCopy is set, the returned array will always be a new instance. - */ - public static function PickRandomSet(a:Array, n:int, forceCopy:Boolean=false):Array - { - if (a.length <= n || a.length == 0) - { - if (forceCopy) return a.concat(); - else return a; - } - if (n == 1) return [PickRandom(a)]; - - var shuffled:Array = GetShuffledArray(a); - return shuffled.slice(0, n); - } - - /** - * Does not randomly sort an array! To do that, Use the default array.sort with this as its argument. - * If you want a new, shuffled array, use GetShuffledArray - */ - public static function randomSort(a:*, b:*) : Number - { - if (Math.random() < 0.5) return -1; - else return 1; - } - - /** - * Returns the union of arr1 and arr2. If the elements are not primitive types, you'll need to provide a sorting function. - * If inPlace, a1 and a2 will be sorted. - * If they already contain duplicates, then all bets are off. - */ - public static function MergeArrays(arr1:Array, arr2:Array, sortFunc:Function = null, inPlace:Boolean = false) : Array - { - var ret:Array = []; - var a1:Array = (inPlace) ? arr1 : arr1.slice(); - var a2:Array = (inPlace) ? arr2 : arr2.slice(); - - var len1:uint = a1.length; - var len2:uint = a2.length; - var i1:uint = 0; - var i2:uint = 0; - - //Boring cases - if (len1 == 0 && len2 == 0) return ret; - if (len1 == 0) return (inPlace) ? a2.slice() : a2; - if (len2 == 0) return (inPlace) ? a1.slice() : a1; - - if (sortFunc) - { - a1.sort(sortFunc); - a2.sort(sortFunc); - } - else - { - a1.sort(); - a2.sort(); - } - - while (i1 < len1) - { - //add all from a2 up to a1[i1] - while (i2 < len2 && a2[i2] <= a1[i1]) - { - ret.push(a2[i2]); - i2 += 1; - } - if (ret.length == 0 || a1[i1] != ret[ret.length-1]) ret.push(a1[i1]); - i1 += 1; - } - - while (i2 < len2) ret.push(a2[i2]); - - return ret; - } - - public static function ConvertToHHMMSS(seconds:Number):String - { - var s:Number = seconds % 60; - var m:Number = Math.floor((seconds % 3600 ) / 60); - var h:Number = Math.floor(seconds / (60 * 60)); - - var hourStr:String = (h == 0) ? "" : DoubleDigitFormat(h) + ":"; - var minuteStr:String = DoubleDigitFormat(m) + ":"; - var secondsStr:String = DoubleDigitFormat(s); - - return hourStr + minuteStr + secondsStr; - } - - public static function DoubleDigitFormat(num:uint):String - { - if (num < 10) - { - return ("0" + num); - } - return String(num); - } - - public static function CapitolizeString(str:String) : String - { - var firstChar:String = str.substr(0, 1); - var restOfString:String = str.substr(1, str.length); - - return firstChar.toUpperCase()+restOfString.toLowerCase(); - } - - // ^ Nice spelling, goof! - public static function CapitalizeString(str:String) : String - { - return CapitolizeString(str); - } - - public static function GetListString(listStrings:Array) : String - { - var andString:String = "&"; - var count:int = 0; - - var listString:String = ""; - for (var i = 0; i < listStrings.length; i++) - { - if (count > 0 && listStrings.length == 2) listString += " "+andString+" "; // For just 2 items - else if (count == listStrings.length-1 && listStrings.length > 2) - { - // For adding "and" at the end of 3+ items. It is: ", and $(item)" - var endingString:String = ""; - endingString = endingString.replace("$(item)", listStrings[i]); - listString += endingString; - count++; - continue; - } - else if (count > 0) listString += ", "; // Comma separated list - - listString += listStrings[i]; - count++; - } - - return listString; - } - - /* - * Flash doesn't like the way MySQL prints dates (2016-06-02 13:00:00) - * "The year month and day terms can be separated by a forward slash (/) or by spaces, but never by a dash (-)." - */ - public static function ParseDate (dateString:String) : Date - { - var pattern:RegExp = /-/g; - var date = new Date(); - dateString = dateString.replace(pattern, "/"); - date.setTime(Date.parse(dateString)); - return date; - } - - /* - * For display only, not intended to be read by ParseDate - * Tuesday, June 7th, 2016 at 10:32 AM - */ - public static function FormatDate (date:Date) : String - { - var f:DateTimeFormatter = new DateTimeFormatter("en-US"); - var dateStr:String; - var lastChar:String; - - //Flash can't do "1st", "2nd", etc - - f.setDateTimePattern("d"); - dateStr = f.format(date); - lastChar = dateStr.charAt(dateStr.length - 1); - - if (lastChar == "1" && dateStr != "11") dateStr += "st"; - else if (lastChar == "2" && dateStr != "12") dateStr += "nd"; - else if (lastChar == "3" && dateStr != "13") dateStr += "rd"; - else dateStr += "th"; - - f.setDateTimePattern("EEEE, MMMM '" + dateStr + "', yyyy 'at' h:mm a"); - return f.format(date); - } - - /* Simply counts the number of properties on the object - */ - public static function CountObjectParameters(obj:Object):int - { - var cnt:int=0; - - for (var s:String in obj) cnt++; - - return cnt; - } - - /** - * For when shit gets real - */ - public static function PrintStackTrace() - { - try { - throw new Error('StackTrace'); - } catch (e:Error) { - _strace(e.getStackTrace()); - } - } - } -} \ No newline at end of file diff --git a/org/aszip/compression/CompressionMethod.as b/org/aszip/compression/CompressionMethod.as deleted file mode 100644 index 42fe7a0..0000000 --- a/org/aszip/compression/CompressionMethod.as +++ /dev/null @@ -1,17 +0,0 @@ -package org.aszip.compression - -{ - - /** - * The CompressionMethod class lets you choose the compression algorithms used for the files in the ZIP. - */ - public class CompressionMethod - - { - - public static var GZIP:String = 'GZIP'; - public static var NONE:String = 'NONE'; - - } - -} \ No newline at end of file diff --git a/org/aszip/crc/CRC32.as b/org/aszip/crc/CRC32.as deleted file mode 100644 index fcbc4f0..0000000 --- a/org/aszip/crc/CRC32.as +++ /dev/null @@ -1,63 +0,0 @@ -/** -* AS3 CRC32 algorithm implementation -*/ - -package org.aszip.crc -{ - - import flash.utils.ByteArray; - - public class CRC32 { - - private var crc32:int; - private static var CRCTable:Array = initLookupTable(); - - private static function initLookupTable ():Array - { - - var polynomial:int = 0xEDB88320; - var CRC32Table:Array = new Array(256); - - var i:int = 256; - var j:int = 8; - - while ( i-- ) - - { - - var crc:int = i; - - while ( j-- ) crc = (crc & 1) ? (crc >>> 1) ^ polynomial : (crc >>> 1); - - j = 8; - - CRC32Table [ i ] = crc; - - } - - return CRC32Table; - - } - - public function generateCRC32 ( pBytes:ByteArray ):void - { - - var length:int = pBytes.length; - - var crc:int = ~crc32; - - for ( var i:int = 0; i < length; i++ ) crc = ( crc >>> 8 ) ^ CRCTable[ pBytes[i] ^ (crc & 0xFF) ]; - - crc32 = ~crc; - - } - - public function getCRC32 ():int - { - - return crc32 & 0xFFFFFFFF; - - } - - } -} \ No newline at end of file diff --git a/org/aszip/encoding/PNGEnc.as b/org/aszip/encoding/PNGEnc.as deleted file mode 100644 index 9847cd6..0000000 --- a/org/aszip/encoding/PNGEnc.as +++ /dev/null @@ -1,218 +0,0 @@ -/** -* PNG encoding class from kaourantin.net, optimised by 5etdemi.com/blog -* @author kaourantin -* @version 0.1 -*/ - -package org.aszip.encoding -{ - import flash.utils.ByteArray; - import flash.display.BitmapData; - import flash.utils.getTimer; - import flash.geom.Rectangle; - - public class PNGEnc { - - public static function encode(img:BitmapData, type:uint = 0):ByteArray { - - - - // Create output byte array - var png:ByteArray = new ByteArray(); - // Write PNG signature - png.writeUnsignedInt(0x89504e47); - png.writeUnsignedInt(0x0D0A1A0A); - // Build IHDR chunk - var IHDR:ByteArray = new ByteArray(); - IHDR.writeInt(img.width); - IHDR.writeInt(img.height); - if(img.transparent || type == 0) - { - IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA - } - else - { - IHDR.writeUnsignedInt(0x08020000); //24bit RGB - } - IHDR.writeByte(0); - writeChunk(png,0x49484452,IHDR); - // Build IDAT chunk - var IDAT:ByteArray= new ByteArray(); - - switch(type) - { - case 0: - writeRaw(img, IDAT); - break; - case 1: - writeSub(img, IDAT); - break; - } - - IDAT.compress(); - writeChunk(png,0x49444154,IDAT); - // Build IEND chunk - writeChunk(png,0x49454E44,null); - // return PNG - - - - return png; - } - - private static function writeRaw(img:BitmapData, IDAT:ByteArray):void - { - var h:int = img.height; - var w:int = img.width; - var transparent:Boolean = img.transparent; - - for(var i:int=0;i < h;i++) { - // no filter - if ( !transparent ) { - var subImage:ByteArray = img.getPixels( - new Rectangle(0, i, w, 1)); - //Here we overwrite the alpha value of the first pixel - //to be the filter 0 flag - subImage[0] = 0; - IDAT.writeBytes(subImage); - //And we add a byte at the end to wrap the alpha values - IDAT.writeByte(0xff); - } else { - IDAT.writeByte(0); - var p:uint; - for(var j:int=0;j < w;j++) { - p = img.getPixel32(j,i); - IDAT.writeUnsignedInt( - uint(((p&0xFFFFFF) << 8)| - (p>>>24))); - } - } - } - } - - private static function writeSub(img:BitmapData, IDAT:ByteArray):void - { - var r1:uint; - var g1:uint; - var b1:uint; - var a1:uint; - - var r2:uint; - var g2:uint; - var b2:uint; - var a2:uint; - - var r3:uint; - var g3:uint; - var b3:uint; - var a3:uint; - - var p:uint; - var h:int = img.height; - var w:int = img.width; - - for(var i:int=0;i < h;i++) { - // no filter - IDAT.writeByte(1); - if ( !img.transparent ) { - r1 = 0; - g1 = 0; - b1 = 0; - a1 = 0xff; - for(var j:int=0;j < w;j++) { - p = img.getPixel(j,i); - - r2 = p >> 16 & 0xff; - g2 = p >> 8 & 0xff; - b2 = p & 0xff; - - r3 = (r2 - r1 + 256) & 0xff; - g3 = (g2 - g1 + 256) & 0xff; - b3 = (b2 - b1 + 256) & 0xff; - - IDAT.writeByte(r3); - IDAT.writeByte(g3); - IDAT.writeByte(b3); - - r1 = r2; - g1 = g2; - b1 = b2; - a1 = 0; - } - } else { - r1 = 0; - g1 = 0; - b1 = 0; - a1 = 0; - for(var k:int=0;k < w;k++) { - p = img.getPixel32(k,i); - - a2 = p >> 24 & 0xff; - r2 = p >> 16 & 0xff; - g2 = p >> 8 & 0xff; - b2 = p & 0xff; - - r3 = (r2 - r1 + 256) & 0xff; - g3 = (g2 - g1 + 256) & 0xff; - b3 = (b2 - b1 + 256) & 0xff; - a3 = (a2 - a1 + 256) & 0xff; - - IDAT.writeByte(r3); - IDAT.writeByte(g3); - IDAT.writeByte(b3); - IDAT.writeByte(a3); - - r1 = r2; - g1 = g2; - b1 = b2; - a1 = a2; - } - } - } - } - - private static var crcTable:Array; - private static var crcTableComputed:Boolean = false; - - private static function writeChunk(png:ByteArray, - type:uint, data:ByteArray):void { - if (!crcTableComputed) { - crcTableComputed = true; - crcTable = []; - for (var n:uint = 0; n < 256; n++) { - //var c:uint = n; - for (var k:uint = 0; k < 8; k++) { - if (n & 1) { - c = uint(uint(0xedb88320) ^ - uint(c >>> 1)); - } else { - c = uint(c >>> 1); - } - } - crcTable[n] = c; - } - } - var len:uint = 0; - if (data != null) { - len = data.length; - } - png.writeUnsignedInt(len); - var p:uint = png.position; - png.writeUnsignedInt(type); - if ( data != null ) { - png.writeBytes(data); - } - var e:uint = png.position; - png.position = p; - var c:uint = 0xffffffff; - for (var i:int = 0; i < (e-p); i++) { - c = uint(crcTable[ - (c ^ png.readUnsignedByte()) & - 0xff] ^ (c >>> 8)); - } - c = uint(c^uint(0xffffffff)); - png.position = e; - png.writeUnsignedInt(c); - } - } -} \ No newline at end of file diff --git a/org/aszip/saving/Download.as b/org/aszip/saving/Download.as deleted file mode 100644 index 52cbb0a..0000000 --- a/org/aszip/saving/Download.as +++ /dev/null @@ -1,14 +0,0 @@ -package org.aszip.saving - -{ - - public class Download - - { - - public static const ATTACHMENT:String = "attachment"; - public static const INLINE:String = "inline"; - - } - -} \ No newline at end of file diff --git a/org/aszip/saving/Method.as b/org/aszip/saving/Method.as deleted file mode 100644 index 208a254..0000000 --- a/org/aszip/saving/Method.as +++ /dev/null @@ -1,14 +0,0 @@ -package org.aszip.saving - -{ - - public class Method - - { - - public static const LOCAL:String = "local"; - public static const REMOTE:String = "remote"; - - } - -} \ No newline at end of file diff --git a/org/aszip/zip/ASZip.as b/org/aszip/zip/ASZip.as deleted file mode 100644 index a63a9d2..0000000 --- a/org/aszip/zip/ASZip.as +++ /dev/null @@ -1,366 +0,0 @@ -/** -* This class lets you generate zip files in AS3 -* AS3 implementation of the following PHP script : -* http://www.zend.com/zend/spotlight/creating-zip-files1.php?article=creating-zip-files1&kind=sl&id=274&open=1&anc=0&view=1 -* -* @author Thibault Imbert (bytearray.org) -* @usage Compression methods for the files : -* -* CompressionMethod.NONE = no compression is applied -* CompressionMethod.GZIP = native GZIP compression is applied -* -* first parameter : compression method -* -* var myZip:ASZIP = new ASZIP ( CompressionMethod.GZIP ); -* -* @version 0.1 First release -* @version 0.2 ASZip.saveZIP method added -*/ - -package org.aszip.zip -{ - - import flash.accessibility.Accessibility; - import flash.utils.ByteArray; - import flash.utils.Endian; - import flash.net.URLRequest; - import flash.net.URLRequestHeader; - import flash.net.URLRequestMethod; - import flash.net.navigateToURL; - import org.aszip.saving.Method; - import org.aszip.compression.CompressionMethod; - import org.aszip.crc.CRC32; - - /** - * The ASZip class represents a Zip file - */ - public class ASZip - - { - - /** - * The compressed data buffer - */ - private var compressedData:ByteArray; - /** - * The central directory - */ - private var centralDirectory:ByteArray; - /** - * The central index - */ - private var oldOffset:Number - /** - * Number of directories in the zip - */ - private var nbDirectory:Array; - /** - * The final zip stream - */ - private var output:ByteArray; - /** - * The compression method used - */ - private var compressionMethod:String; - /** - * The comment string - */ - private var comment:String; - - /** - * Lets you create a Zip file - * - * @param pCompression Compression method - * @example - * This example shows how to create a valid ZIP file : - *
- *
-		* 
-		* var myZip:ASZip = new ASZip ( CompressionMethod.GZIP );
-		* 
- *
- */ - public function ASZip ( pCompression:String='GZIP' ) - - { - - compressedData = new ByteArray; - centralDirectory = new ByteArray; - output = new ByteArray; - nbDirectory = new Array - comment = new String;; - oldOffset = 0; - compressionMethod = pCompression; - - } - - /** - * Lets you create a directory for the current Zip - * - * @param directoryName Name of the directory - * @example - * This example shows how to create a directory and subdirectory : - *
- *
-		* 
-		* myZip.addDirectory ( "images" );
-		* myZip.addDirectory ( "images/funk" );
-		* 
- *
- */ - public function addDirectory ( directoryName:String ):void - - { - - directoryName = directoryName.split ('\\').join ('/'); - - var feedArrayRow:ByteArray = new ByteArray; - feedArrayRow.endian = Endian.LITTLE_ENDIAN; - feedArrayRow.writeUnsignedInt ( 0x04034b50 ); - feedArrayRow.writeShort ( 0x000a ); - feedArrayRow.writeShort ( 0x0000 ); - feedArrayRow.writeShort ( 0x0000 ); - feedArrayRow.writeUnsignedInt ( unixToDos ( new Date().getTime() ) ); - - feedArrayRow.writeUnsignedInt (0); - feedArrayRow.writeUnsignedInt (0); - feedArrayRow.writeUnsignedInt (0); - feedArrayRow.writeShort ( directoryName.length ); - feedArrayRow.writeShort ( 0 ); - feedArrayRow.writeUTFBytes ( directoryName ); - - feedArrayRow.writeUnsignedInt ( 0 ); - feedArrayRow.writeUnsignedInt ( 0 ); - feedArrayRow.writeUnsignedInt ( 0 ); - - compressedData.writeBytes ( feedArrayRow ); - - var newOffset:int = this.compressedData.length; - - // Directory header - var addCentralRecord:ByteArray = new ByteArray; - addCentralRecord.endian = Endian.LITTLE_ENDIAN; - addCentralRecord.writeUnsignedInt ( 0x02014b50 ); - addCentralRecord.writeShort ( 0x0000 ); - addCentralRecord.writeShort ( 0x000a ); - addCentralRecord.writeShort ( 0x0000 ); - addCentralRecord.writeShort ( 0x0000 ); - addCentralRecord.writeUnsignedInt ( 0x00000000 ); - addCentralRecord.writeUnsignedInt ( 0 ); - addCentralRecord.writeUnsignedInt ( 0 ); - addCentralRecord.writeUnsignedInt ( 0 ); - addCentralRecord.writeShort ( directoryName.length ); - addCentralRecord.writeShort ( 0 ); - addCentralRecord.writeShort ( 0 ); - addCentralRecord.writeShort ( 0 ); - addCentralRecord.writeShort ( 0 ); - addCentralRecord.writeUnsignedInt ( 16 ); - addCentralRecord.writeUnsignedInt ( this.oldOffset ); - - this.oldOffset = newOffset; - - addCentralRecord.writeUTFBytes (directoryName); - - this.nbDirectory.push ( addCentralRecord ); - this.centralDirectory.writeBytes ( addCentralRecord ); - - } - - /** - * Lets you add a file into a specific directory - * - * @param pBytes File stream - * @param pDirectory Directory name - * @example - * This example shows how to add files into directories : - *
- *
-		* 
-		* myZip.addFile ( imageByteArray, "images/image.jpg" );
-		* myZip.addFile ( imageByteArray, "images/funk/image.jpg" );
-		* 
- *
- */ - public function addFile ( pBytes:ByteArray, pDirectory:String ):void - - { - - pDirectory = pDirectory.split ('\\').join ('/'); - - var feedArrayRow:ByteArray = new ByteArray; - feedArrayRow.endian = Endian.LITTLE_ENDIAN; - - // Local File Header - feedArrayRow.writeUnsignedInt ( 0x04034b50 ); - feedArrayRow.writeShort ( 0x0014 ); - feedArrayRow.writeShort ( 0x0000 ); - - // File is deflated - feedArrayRow.writeShort ( this.compressionMethod == CompressionMethod.GZIP ? 0x0008 : 0x0000 ); - - feedArrayRow.writeUnsignedInt ( unixToDos ( new Date().getTime() ) ); - - var uncompressedLength:Number = pBytes.length; - - // CRC32 checksum - var crc:CRC32 = new CRC32; - crc.generateCRC32 ( pBytes ); - var compression:int = crc.getCRC32(); - - // If GZIP compression - if ( compressionMethod == CompressionMethod.GZIP ) - - { - - pBytes.compress(); - var copy:ByteArray = new ByteArray; - copy.writeBytes ( pBytes, 0, pBytes.length - 4 ); - var finalCopy:ByteArray = new ByteArray; - finalCopy.writeBytes ( copy, 2 ); - pBytes = finalCopy; - - } - - var compressedLength:int = pBytes.length; - - feedArrayRow.writeUnsignedInt ( compression ); - feedArrayRow.writeUnsignedInt ( compressedLength ); - feedArrayRow.writeUnsignedInt ( uncompressedLength ); - feedArrayRow.writeShort ( pDirectory.length ); - feedArrayRow.writeShort ( 0 ); - feedArrayRow.writeUTFBytes ( pDirectory ); - feedArrayRow.writeBytes ( pBytes ); - - // Data Descriptor - feedArrayRow.writeUnsignedInt ( compression ); - feedArrayRow.writeUnsignedInt ( compressedLength ); - feedArrayRow.writeUnsignedInt ( uncompressedLength ); - - compressedData.writeBytes ( feedArrayRow ); - - var newOffset:int = compressedData.length; - - // File header - var addCentralRecord:ByteArray = new ByteArray; - addCentralRecord.endian = Endian.LITTLE_ENDIAN; - addCentralRecord.writeUnsignedInt ( 0x02014b50 ); - addCentralRecord.writeShort ( 0x0000 ); - addCentralRecord.writeShort ( 0x0014 ); - addCentralRecord.writeShort ( 0x0000 ); - addCentralRecord.writeShort ( this.compressionMethod == CompressionMethod.GZIP ? 0x0008 : 0x0000 ); - addCentralRecord.writeUnsignedInt ( unixToDos ( new Date().getTime() ) ); - addCentralRecord.writeUnsignedInt ( compression ); - addCentralRecord.writeUnsignedInt ( compressedLength ); - addCentralRecord.writeUnsignedInt ( uncompressedLength ); - addCentralRecord.writeShort(pDirectory.length); - addCentralRecord.writeShort ( 0 ); - addCentralRecord.writeShort ( 0 ); - addCentralRecord.writeShort ( 0 ); - addCentralRecord.writeShort ( 0 ); - addCentralRecord.writeUnsignedInt( 32 ); - - addCentralRecord.writeUnsignedInt ( this.oldOffset ); - this.oldOffset = newOffset; - - addCentralRecord.writeUTFBytes (pDirectory); - - this.nbDirectory.push ( addCentralRecord ); - this.centralDirectory.writeBytes ( addCentralRecord ); - - } - - /** - * Lets you add a comment into the Zip file - * - * @param pComment The comment string to add - * @example - * This example shows how to add a comment for the current zip : - *
myZip.addComment ( "Hello there !");
- */ - public function addComment ( pComment:String ):void - - { - - comment = pComment; - - } - - /** - * Lets you finalize and save the ZIP file and make it available for download - * - * @param pMethod Can be se to Method.LOCAL, the saveZIP will return the ZIP ByteArray. When Method.REMOTE is passed, just specify the path to the create.php file - * @param pURL The url of the create.php file - * @param pDownload Lets you specify the way the ZIP is going to be available. Use Download.INLINE if you want the ZIP to be directly opened, use Download.ATTACHMENT if you want to make it available with a save-as dialog box - * @param pName The name of the ZIP, only available when Method.REMOTE is used - * @return The ByteArray ZIP when Method.LOCAL is used, otherwise the method returns null - * @example - * This example shows how to save the ZIP with a download dialog-box : - *
- *
-		* 
-		* myZIP.saveZIP ( Method.REMOTE, 'create.php', Download.ATTACHMENT, 'archive.zip' );
-		* 
- *
- */ - public function saveZIP ( pMethod:String, pURL:String='', pDownload:String='inline', pName:String='archive.zip' ):* - - { - - output = new ByteArray; - output.endian = Endian.LITTLE_ENDIAN; - output.writeBytes ( this.compressedData ); - output.writeBytes ( this.centralDirectory ); - output.writeUnsignedInt ( 0x06054b50 ); - output.writeUnsignedInt ( 0x00000000 ); - output.writeShort ( this.nbDirectory.length ); - output.writeShort ( this.nbDirectory.length ); - output.writeUnsignedInt ( this.centralDirectory.length ); - output.writeUnsignedInt ( this.compressedData.length ); - output.writeShort ( comment.length ); - writeUTFChars ( comment ); - - if ( pMethod == Method.LOCAL ) return output; - - var header:URLRequestHeader = new URLRequestHeader ("Content-type", "application/octet-stream"); - var myRequest:URLRequest = new URLRequest ( pURL+'?name='+pName+'&method='+pDownload ); - myRequest.requestHeaders.push (header); - myRequest.method = URLRequestMethod.POST; - myRequest.data = saveZIP ( Method.LOCAL ); - - navigateToURL ( myRequest, "_blank" ); - - return null; - - } - - /* - * - * PRIVATE MEMBERS - * - */ - - private function writeUTFChars ( pString:String ):void - - { - - var lng:int = pString.length; - - for (var i:int = 0; i> 1); - - } - - } - -} \ No newline at end of file